先看 HTML:
<ul id="catagory">
<li><a href="https:///menu/jquery/" target="_blank">jQuery</a></li>
<li><a href="https:///menu/aspnet/" target="_blank">Asp.net</a></li>
<li><a href="https:///menu/sqlserver/" target="_blank">Sql Server</a></li>
<li><a href="https:///menu/webqd/" target="_blank">CSS</a></li>
</ul>
要做的效果是:滑鼠移到 a 上時向右滑出一段距離,移開再歸位。直白的寫法:
$(document).ready(function() {
$("#catagory a").hover(function() {
$(this).animate({ paddingLeft: "20px" }, { queue: false, duration: 500 });
}, function() {
$(this).animate({ paddingLeft: "0" }, { queue: true, duration: 500 });
});
});
問題是這段邏輯綁死了 id、也綁死了具體數值。把它包成插件,就能在別的專案裡重複使用,還能自由調整位移量與高亮顏色。
這是一個值得記下來的通用結構:
//用匿名函數包裹,避免污染全域
(function($) {
//把方法擴充到 jQuery
$.fn.extend({
//插件名稱
pluginname: function() {
//遍歷匹配元素的集合
return this.each(function() {
//在這裡編寫處理邏輯
});
}
});
})(jQuery); //傳入 jQuery,函數內就能自由使用 $
(function ($) {
$.fn.extend({
paddingList: function (options) {
//參數與預設值
var defaults = {
animatePadding: 10,
hoverColor: "Black"
};
var options = $.extend(defaults, options);
return this.each(function () {
var o = options;
var obj = $(this); //本例中是 ul 物件
var items = $("li a", obj); //取得 ul 中的 a
items.hover(function () {
$(this).css("color", o.hoverColor);
//queue false 表示不加入動畫佇列
$(this).animate({ paddingLeft: o.animatePadding }, { queue: false, duration: 300 });
}, function () {
$(this).css("color", "");
$(this).animate({ paddingLeft: "0" }, { queue: true, duration: 300 });
});
});
}
});
})(jQuery);
$(document).ready(function() {
$("#catagory").paddingList({ animatePadding: 30, hoverColor: "Red" });
});
效果如下: