本文章介紹了一種比較常用的效果,那就是當滑鼠滑過連結的時候,能夠出現跟隨滑鼠指標移動的圖層,在實際應用中,一般是對於連結的一些解說文字或者圖片等等,下面是代碼執行個體:
<!DOCTYPE html><html><head><meta charset="gb2312"><title>雲棲社區</title><style type="text/css">body{ margin:0; padding:40px; background:#fff; font:80% Arial, Helvetica, sans-serif; color:#555; line-height:180%;}a{ text-decoration:none; color:#f30; }p{ clear:both; margin:0; padding:.5em 0;}img{border:none;}#screenshot{ position:absolute; border:1px solid #ccc; background:#333; padding:5px; display:none; color:#fff;}</style><script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script><script type="text/javascript">this.screenshotPreview=function(){ xOffset = 10; yOffset = 30; $("a.screenshot").hover(function(e){ this.t = this.title; var c = (this.t != "") ? "<br/>" + this.t : ""; $("body").append("<p id='screenshot'><img src='"+this.rel+"' />"+c+"</p>"); $("#screenshot") .css("top",(e.pageY - xOffset) + "px") .css("left",(e.pageX + yOffset) + "px") .fadeIn("fast"); }, function(){ this.title = this.t; $("#screenshot").remove(); }); $("a.screenshot").mousemove(function(e){ $("#screenshot") .css("top",(e.pageY-xOffset)+"px") .css("left",(e.pageX+yOffset)+"px"); }); };$(document).ready(function(){ screenshotPreview();});</script></head><body><a href="#" class="screenshot" title="螞蟻部落" rel="mytest/demo/thesmall.jpg">螞蟻部落</a>歡迎您</body></html>
效果圖:
以上代碼實現了我們的要求,下面簡單介紹一下實現過程:
代碼注釋:
1.this.screenshotPreview=function(){ },聲明一個函數用來實現跟隨效果,在本效果中,this其實是可以省略,它指向window。
2.xOffset=10,聲明一個變數,用來規定滑鼠指標距離彈出圖片的橫向距離。
3.yOffset=30,聲明一個變數,用來規定滑鼠指標距離彈出圖片的縱向距離。
4.$("a.screenshot").hover(function(e){},function(e){}),規定當滑鼠移到連結和離開連結所要執行的函數。
5.this.t = this.title,將連結的title屬性值賦值給t屬性,這裡的this是指向當前滑鼠懸浮的連結化物件。
6.var c = (this.t != "") ? "<br/>" + this.t : "",如果this.t不為空白,也就是存在title屬性值,那麼插入一個分行符號並且串連當前標題內容,否則將c設定為空白。
7.$("body").append("<p id='screenshot'><img src='"+ this.rel +"'/>"+ c +"</p>"),將圖片和相關說明添加到body。
8.$("#screenshot").css("top",(e.pageY-xOffset)+"px").css("left",(e.pageX+yOffset)+"px").fadeIn("fast"),設定p元素的top和left屬性值,並且採用淡入效果展現。
9.this.title=this.t,將title內容賦值給this.title,其實不要這一句也沒有任何問題,有點多餘。
10.$("#screenshot").remove(),移出p元素。
11.$("a.screenshot").mousemove(function(e){}),用來設定當滑鼠指標移動時,圖片能夠跟隨。
12.$("#screenshot").css("top",(e.pageY-xOffset)+"px") .css("left",(e.pageX+yOffset)+"px"),設定p元素的top和left屬性值,能夠實現跟隨效果。
以上就是本文的全部內容,希望對大家的學習有所協助。