本章節介紹一下一種比較常用的效果,那就是當鼠標滑過鏈接的時候,能夠出現跟隨鼠標指針移動的圖層,在實際應用中,一般是對于鏈接的一些說明文字或者圖片等等,
我們先來看個演示圖
下面是代碼實例:
<link rel="stylesheet" type="text/css" /> <script type="text/javascript" src="http://www.gimoo.net/t/js/jquery-1.2.6.pack.js"></script> <script type="text/javascript" src="http://www.gimoo.net/t/js/jquery.imagePreview.1.0.js"></script> <script type="text/javascript"> $(function(){ $("a.preview").preview(); }); </script> <style type="text/css"> html{overflow-y:scroll;} a.preview,a.preview:hover{text-decoration:none;} a.preview img{margin:20px 10px;} </style> </head> <body> <div class="zxx_out_box"> <div class="zxx_in_box"> <h3 class="zxx_title">圖片放大顯示的jQuery插件演示頁面</h3> <div class="zxx_main_con"> <div class="zxx_test_list"> <a class="preview" title="張含韻"> <img src="http://image.gimoo.net/image/study/s/s128/mm1.jpg" /> </a> <a class="preview" title="某不知名美女"> <img src="http://image.gimoo.net/image/study/s/s128/mm2.jpg" /> </a> <a class="preview" title="某不知名美女"> <img src="http://image.gimoo.net/image/study/s/s128/mm3.jpg" /> </a> <a class="preview" title="某不知名美女"> <img src="http://image.gimoo.net/image/study/s/s128/mm4.jpg" /> </a> <a class="preview" title="某不知名美女"> <img src="http://image.gimoo.net/image/study/s/s128/mm5.jpg" /> </a> </div> </div> </div> </div> </body> </html>
以上代碼實現了我們的要求,小伙伴們覺著怎么樣呢
接下來我們看看使用方法簡要說明:
1.需要借助a標簽的href屬性,此jQuery插件的原理是當鼠標移至縮略圖(或鏈接文字時),會加載一段含有href指向路徑的大圖html片段,該片段根據鼠標的位置絕對定位。于是產生了鼠標移到縮略圖上顯示大圖的效果。大圖的地址就是a標簽的href屬性的內容。例如:<a href=”xx.jpg”>縮略圖</a> 如果此a標簽含有顯示大圖的方法,則頁面就會顯示href所指向的“xx.jpg”這個圖片。
2.使用的方法是:目標選擇器.preview();例如上面的<a href=”xx.jpg”>縮略圖</a>就可以使用$(“a”).preview();這段代碼實現鼠標移到“縮略圖”這個文字鏈接上顯示xx.jpg這張圖片的效果。
3.僅支持png,gif,jpg,bmp四種格式的圖片,您可以修改插件代碼的正則表達式擴展支持的圖片格式類型。
下面簡單介紹一下實現過程:
一.代碼注釋:
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='http://www.gimoo.net/t/1904/5ca446ba2956a.html"+ 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屬性值,能夠實現跟隨效果。
二.相關閱讀:
1.hover()函數可以參閱jQuery的hover事件一章節。
2.append()函數可以參閱jQuery的append()方法一章節。
3.css()函數可以參閱jQuery的css()方法一章節。
4.pageY屬性可以參閱jQuery的event.pageY屬性一章節。
5.fadeIn()函數可以參閱jQuery的fadeIn()方法一章節。
6.remove()函數可以參閱jQuery的remove()方法一章節。
7.mousemove事件可以參閱jQuery的mousemove事件一章節。