html部分css
//小圖 <div id="photoBox"> <img src="圖片路徑" width="400" height="400"> <div id="dow"></div> </div> //大圖 <div id="bigPhotoBox"></div>
css部分html
#photoBox { border: 1px solid #ccc; //小圖位置,這裏改 position: absolute; } #photoBox img { display: block; } #dow { width: 100px; height: 100px; background-color: rgba(0, 0, 0, 0.6); position: absolute; display: none; } #bigPhotoBox { display: none; border: 1px solid #ccc; background-repeat: no-repeat; background-color: #fff; width: 400px; height: 400px; //大圖位置,這裏改 position: absolute; top: 0; left: 400px; }
js部分優化
//小圖id $("#photoBox").Magnifier({ //大圖id renderTo: "#bigPhotoBox", });
jq插件部分this
(function($) { $.fn.Magnifier = function(setting) { if(setting && setting.renderTo) { if(typeof(setting.renderTo) == "string") { setting.renderTo = $(setting.renderTo); } } else { return; } var x, y, set; this.on("mousemove", function(event) { x = event.pageX - 50; y = event.pageY - 50; //陰影框實際移動範圍 if(x > 0 && x < 300 && y > 0 && y < 300) { set = x / 3 + "% " + y / 3 + "%"; setting.renderTo.css({ backgroundPosition: set }); $("#dow").css({ top: y, left: x, }) } if(y <= 300 && y >= 0) { if(x < 0) { set = 0 + "% " + y / 3 + "%"; setting.renderTo.css({ backgroundPosition: set }); $("#dow").css({ top: y, left: 0, }) } if(x > 300) { set = 100 + "% " + y / 3 + "%"; setting.renderTo.css({ backgroundPosition: set }); $("#dow").css({ top: y, left: 300, }) } } if(x <= 300 && x >= 0) { if(y < 0) { set = x / 3 + "% " + 0 + "%"; setting.renderTo.css({ backgroundPosition: set }); $("#dow").css({ top: 0, left: x, }) } if(y > 300) { set = x / 3 + "% " + 100 + "%"; setting.renderTo.css({ backgroundPosition: set }); $("#dow").css({ top: 300, left: x, }) } } }); //鼠標移入移出效果 this.hover(function() { setting.renderTo.css({ display: "block", backgroundImage: "url(" + $("#photoBox img").attr("src") + ")" }); $("#dow").css({ display: "block" }) }, function() { setting.renderTo.css({ display: "none" }); $("#dow").css({ display: "none" }) }); } })(jQuery);
一時興起寫了這個插件,用的時候卻是簡單,只需引入JQ插件再加上寫少許JS代碼代碼就好了,大小圖片的位置能夠在CSS裏改,惟一麻煩的是,圖片寬高的更改問題,圖片的寬高是400px的固定值,若是圖片不是正方形,圖片會失真;且CSS裏面是這麼寫的,JQ裏也是,因爲這個數值涉及到陰影框的移動範圍,改起來比較麻煩。因此就先這樣吧,等之後有時間再優化優化。url