前陣子寫過一篇圖片「上一張/下一張」連結效果的文章,後來看到 jQuery 外掛封裝,手癢就拿這個例子來練習。
/*
* imageupdown 1.0
* Copyright (c) 2009
* Date: 2010-04-20
* 圖片移動上一張/下一張特效
*/
(function($){
$.fn.imageupdown = function(options){
var defaults = {
upCursor:"pre.cur",
upTitle:"點擊查看上一張",
upUrl:$(this).attr('left'),
downCursor:"next.cur",
downTitle:"點擊查看下一張",
downUrl:$(this).attr('right')
}
var options = $.extend(defaults, options);
this.each(function(){
var thisImage=$(this);
$(thisImage).bind("mousemove",function(e){
var positionX=e.originalEvent.x||e.originalEvent.layerX||0;
if(positionX<=$(this).width()/2){
this.style.cursor='url('+options.upCursor+'),auto';
$(this).attr('title',''+options.upTitle+'');
$(this).parent().attr('href',''+options.upUrl+'');
}else{
this.style.cursor=''+options.downCursor+'';
$(this).attr('title',''+options.downTitle+'');
$(this).parent().attr('href',''+options.downUrl+'');
}
});
});
};
})(jQuery);
<script type="text/javascript">
$(document).ready(function() {
$(".rootclass").imageupdown();
});
</script>
function(e) 中的 e 是什麼?它對應的是事件物件,例如 $().click(function(e){}) 裡的 e 就是 click 事件,$().focus(function(e){}) 裡的 e 則是 focus 事件。透過 e.originalEvent 就能取得滑鼠在圖片上的位置,據此判斷要顯示「上一張」還是「下一張」。