通过js实现京东淘宝商品放大镜页面
HTML样式
<div id="small">
<img src="./img/small.jpg" alt="">
<div id="moveBox"></div>
</div>
<div id="big">
<img src="./img/big.jpg" alt="" id="img">
</div>
css样式
#small {
width: 130px;
height: 130px;
float: left;
margin: 100px;
position: relative;
}
#moveBox {
width: 60px;
height: 40px;
background: rgba(255, 0, 0, 0.2);
position: absolute;
top: 0;
cursor: all-scroll;
display: none;
}
#big {
width: 369px;
height: 246px;
border: 1px solid blue;
overflow: hidden;
position: relative;
top: 100px;
left: 500px;
display: none;
}
#big img {
position: absolute;
}
js样式
var smallBox = document.getElementById('small');
var moveBox = document.getElementById('moveBox');
var bigBox = document.getElementById('big');
var bigImg = document.getElementById('img');
var maxLeft, maxTop;
//鼠标进入
smallBox.onmouseenter = function () {
moveBox.style.display = 'block';
bigBox.style.display = 'block';
maxLeft = smallBox.offsetWidth - moveBox.offsetWidth;//物体可以到达的最大的left值
maxTop = smallBox.offsetHeight - moveBox.offsetHeight;//物体可以到达的最大的top值
};
smallBox.onmouseleave = function () {
moveBox.style.display = 'none';
bigBox.style.display = 'none';
};
//鼠标在smallBox中移动,物体随着移动,显示位置的大图
smallBox.onmousemove = function (e) {
e = e || window.event;
//鼠标在没有超过宽度和高度的一半时,物体不移动
var l = e.clientX - smallBox.offsetLeft - moveBox.offsetWidth / 2
, t = e.clientY - smallBox.offsetTop - moveBox.offsetHeight / 2;
if (l < 0) { //鼠标移动的水平方向没有超过物体的宽度的一半
l = 0;
}
if (t < 0) {//鼠标移动的垂直方向没有超过物体的高度的一半
t = 0;
}
if (l >= maxLeft) {
l = maxLeft;
}
if (t >= maxTop) {
t = maxTop;
}
moveBox.style.left = l + 'px';
moveBox.style.top = t + 'px';
//修改大图的位置
//bigImg的宽度*物体移动的距离 /小Img的宽度
bigImg.style.left = - bigImg.offsetWidth * l / smallBox.offsetWidth +'px';
bigImg.style.top =- bigImg.offsetHeight * t / smallBox.offsetHeight +'px'
};
实现效果:
左边为商品小盒子,红色遮罩为鼠标进入时显示放大区域,右侧为放大效果