js实现放大镜功能
1、效果图 如下:
(ps:代码种的img 均是 我自己项目路径下的图片)
2、html代码:
3、css代码:
* {margin: 0;padding: 0;}
img {
vertical-align: top;
}
.box {
width: 450px;
height: 450px;
margin:100px;
border: 1px solid #ccc;
position: relative;
}
.big {
width: 550px;
height: 550px;
position: absolute;
top: 0;
left: 460px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
.mask {
width: 310px;
height: 310px;
background: rgba(255, 255, 0, 0.4);
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
.small {
position: relative;
}
.big img {
position: absolute;
top: 0;
left: 0;
}
(ps:自己随便写的css样式 无视也行。重点js)
4、js代码 如下:
var fdj = document.getElementById("fdj"); // 获得最大的盒子
var small = fdj.children[0]; // 获得small 小图片 450盒子
var big = fdj.children[1]; // 获得 大图片 800 盒子
var mask = small.children[1]; // 小的黄色盒子
var bigImage = big.children[0]; // 大盒子里面的图片
small.onmouseover = function() { // 鼠标经过显示出他们
mask.style.display = "block";
big.style.display = "block";
}
small.onmouseout = function() {
mask.style.display = "none";
big.style.display = "none";
}
// 鼠标在small 内移动
var x = 0;
var y = 0;
small.onmousemove = function(event) {
var event = event || window.event;
x = event.clientX - this.offsetParent.offsetLeft - mask.offsetWidth /2; // 再某个盒子内的坐标
//alert(this.offsetLeft);
y = event.clientY - this.offsetParent.offsetTop - mask.offsetHeight /2;
if(x < 0)
{
x = 0;
}
else if(x > small.offsetWidth - mask.offsetWidth)
{
x = small.offsetWidth - mask.offsetWidth;
}
if(y<0)
{
y = 0;
}
else if(y > small.offsetHeight - mask.offsetHeight)
{
y = small.offsetHeight - mask.offsetHeight;
}
mask.style.left = x + "px";
mask.style.top = y + "px";
//mask/大盒子 = 小盒子/大图片
bigImage.style.left=-x*big.offsetWidth/mask.offsetWidth+"px";
bigImage.style.top=-y*big.offsetHeight/mask.offsetHeight+"px";
}
这样,就可以通过js实现 类似于淘宝页面关于产品介绍的 放大镜效果。