jQuery对象级插件是通过【jQuery.fn.extend()】增加功能,所增加的函数可以直接被jQuery对象调用。
此示例的功能为:当鼠标悬停在某个li元素上时,该元素背景色会改变,源码如下:
jquery.color.js :
; (function($) {
$.fn.extend({
"focusColor": function(li_col) {
var def_col = '#ccc';
var lst_col = '#fff';
li_col = (li_col === undefined) ? def_col : li_col;
$(this).find('li').each(function() {
$(this).mouseover(function() {
$(this).css('background-color', li_col);
}).mouseout(function() {
$(this).css('background-color', '#fff');
});
});
return $(this);
}
});
}) (jQuery);
index.html :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="js/angular.js"></script>
</head>
<body>
<div>
<div>
<ul id="ul">
<li><span>张三</span></li>
<li><span>李四</span></li>
<li><span>王五</span></li>
</ul>
</div>
</div>
<script src="js/jquery-1.11.3.js"></script>
<script src="js/jquery.color.js"></script>
<script type="text/javascript">
$(function() {
$('ul').focusColor('#888');
});
</script>
</body>
<html>