jq仿淘宝放大镜插件

时间:2023-03-09 01:11:31
jq仿淘宝放大镜插件

html部分

//小图
<div id="photoBox">
<img src="图片路径" width="400" height="400">
<div id="dow"></div>
</div>
//大图
<div id="bigPhotoBox"></div>

css部分

#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:; 
  left: 400px; }

js部分

//小图id
$("#photoBox").Magnifier({
//大图id
renderTo: "#bigPhotoBox",
});

jq插件部分

(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里也是,由于这个数值涉及到阴影框的移动范围,改起来比较麻烦。所以就先这样吧,等以后有时间再优化优化。