本文章介紹了一種比較常用的效果,那就是當鼠標滑過鏈接的時候,能夠出現跟隨鼠標指針移動的圖層,在實際應用中,一般是對于鏈接的一些說明文字或者圖片等等,下面是代碼實例:
<!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屬性值,能夠實現跟隨效果。
以上就是本文的全部內容,希望對大家的學習有所幫助。
新聞熱點
疑難解答