Jquery效果:样式表切换
熟悉的开篇
$(document).ready(function(){
$('.styleswitch').click(function()
$('.styleswitch').click(function()
告诉jQuery“以最快的速度查找所有包含对象名‘styleswitch’的元素,并在他们被鼠标点击时执行一个函数”。
看起来不错。当鼠标点击预先指定的元素时,switchStylestyle函数将被调用。从现在开始是重点。
$('link[@rel*=style]').each(function(i) {
这句话什么意思?
找到了jQuery的作者John Resig,向他咨询。他直接给了我一个jQuery网站的页面地址,里面讲解了若干jQuery提供的高级特性(xpath),可以用来查找并操作页面中的若干元素。如果你看过这些东西你就能明白上面那句神秘的代码的含义是告诉jQuery“查找所有带rel属性并且属性值字符串中包含‘style’的link链接元素”。
让我们看看如何编写包含一个主样式表,两个备用样式表的页面:
1 2 3 | <link rel="stylesheet" type="text/css" href="styles1.css" title="styles1" media="screen" /> <link rel="alternate stylesheet" type="text/css" href="styles2.css" title="styles2" media="screen" /> <link rel="alternate stylesheet" type="text/css" href="styles3.css" title="styles3" media="screen" /> |
我们可以看到所有样式表都含有一个包含‘style’字串的rel属性。 所以结果一目了然,jQuery轻松定位了页面中的样式表链接。
下一步?
each()函数将遍历所有这些样式表链接,并执行下一行中的代码:
this.disabled = true;
if (this.getAttribute('title') == styleName) this.disabled = false;
“首先禁用所有的样式表链接,然后开启任何title属性值与switchStylestyle函数传递过来的字串相同的样式表”
一把抓啊,不过很有效。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $(document).ready(function(){ $('.styleswitch').click(function(){ switchStylestyle(this.getAttribute("rel")); return false; }); var c = readCookie('style'); if (c) switchStylestyle(c); }); function switchStylestyle(styleName){ $('link[@rel*=style]').each(function(i){ this.disabled = true; if (this.getAttribute('title') == styleName) this.disabled = false; }); createCookie('style', styleName, 365); } |
HTML部分
1 2 3 4 5 | <ul> <li><a href="serversideSwitch.html?style=style1" rel="styles1" class="styleswitch">styles1</a></li> <li><a href="serversideSwitch.html?style=style2" rel="styles2" class="styleswitch">styles2</a></li> <li><a href="serversideSwitch.html?style=style3" rel="styles3" class="styleswitch">styles3</a></li> </ul> |
| -欢迎为本文评级 |
No donations within the last 180 days.Who make donation will leave message at here.Donate Now.
This a wordpress plugin Wp-Donators.It provides a smart donation function to autoleave the sponsor information in this container after payment. People can donate and submit name/URL or TextLink AD. The information of the latest donors are displayed in the cloud. The more a person donates, the bigger their link will be.It's will support most popular payment interface in future. ParPal Just the first one. More..
Powered By:WP-DONATORS
相关日志 |
本文读者也关心以下内容:
|















































另一个例子:http://book.learningjquery.com/2509_03_code/carol.html
Reply