您的位置:首页 > Web前端 > JQuery

jquery插件开发学习笔记(四)——导航栏特效

2017-03-30 20:53 696 查看

写在前面

想法是:对于一个导航栏,鼠标悬浮于某一项上时,该项高亮,兄弟项正常。鼠标位于导航栏之外时,所有项目正常。

关键代码

<ul>
<li id="test_1"><a href="">home</a></li>
<li><a href="">java</a></li>
<li><a href="">javascript</a></li>
</ul>


method_:function (options_2) {
var settings_=$.extend({},defaults_2,options_2);
return this.each(function () {
var $this=$(this);
$this.children().mouseover(function () {
$this.children().css({color:settings_.color}).parent().siblings().children().css({color:settings_.color_siblings});
}).mouseleave(function () {
$this.children().css({color:settings_.color_siblings});
});
});
}


$("li").plugin_2("method_",{color:"#ff0",color_siblings:"#f00"});


由于a标签包裹于li标签之内,所以用了几层children()和parent(),逻辑很简单:css样式作用于a标签而不是li标签。

调用插件时可设定高亮色和正常色。比如我所设置的,高亮为红,正常为黄。搭配的整体色调为中国国家队队服:西红柿炒鸡蛋。呵呵呵。

全文代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jquery插件_002</title>
<script src="../../lib/jquery/jquery.js"></script>
<style>
ul{
background-color: #666;
}
li{
display: inline-block;
margin: 16px;
}
a{
text-decoration: none;
}
</style>
</head>
<body>
<nav>
<ul>
<li id="test"><a href="">home</a></li>
<li><a href="">java</a></li>
<li><a href="">javascript</a></li>
</ul>
<br>
<ul> <li id="test_1"><a href="">home</a></li> <li><a href="">java</a></li> <li><a href="">javascript</a></li> </ul>
</nav>

<script>
(function ($) {
//默认方法的默认参数组
var defaults_1={
back:"#777",
back_s:"#af8",
color:"#fff",
color_s:"#ff0",
fontSize:"20px"
};

//导航栏特效的默认参数组
var defaults_2={
color:"#fff",
color_siblings:"#0a0"
};

//插件方法
var methods={
inti:function (options) {
var settings=$.extend({},defaults_1,options);
return this.each(function () {
var $this=$(this);
$this.children().css({color:settings.color,backgroundColor:settings.back})
.parent().siblings().children().css({color:settings.color_s,backgroundColor:settings.back_s});
});
},

//导航栏特效代码
method_:function (options_2) {
var settings_=$.extend({},defaults_2,options_2);
return this.each(function () {
var $this=$(this);
$this.children().mouseover(function () {
$this.children().css({color:settings_.color}).parent().siblings().children().css({color:settings_.color_siblings});
}).mouseleave(function () {
$this.children().css({color:settings_.color_siblings});
});
});
}
};

//定义插件
$.fn.plugin_2=function () {
var method=arguments[0];
if(methods[method]){
method=methods[method];
arguments = Array.prototype.slice.call(arguments, 1);
}else if(typeof method==="object"||!method){
method=methods.inti;
}else{
$.error("error happened!");
return this;
}
return method.apply(this,arguments);
};
})(jQuery);

$("#test").plugin_2({color_s:"#f08"});//调用默认方法
$("li").plugin_2("method_",{color:"#ff0",color_siblings:"#f00"});//调用导航栏特效方法
</script>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: