js模拟实现京东详情页图片放大效果
本文实例为大家分享了js实现京东详情页图片放大的具体代码,供大家参考,具体内容如下
效果:
html:
<div class="preview_img"> <img src="upload/s3.png" alt=""> <div class="mask"></div> <div class="big"> <img src="upload/big.jpg" alt="" class="bigImg"> </div> </div>
css:
.preview_img { position: relative; height: 398px; border: 1px solid #ccc; } .mask { display: none; position: absolute; width: 300px; height: 300px; top: 0; left: 0; background: #FEFE4F; opacity: .5; border: 1px solid #ccc; cursor: move; } .big { display: none; position: absolute; width: 550px; height: 550px; top: 0; left: 410px; z-index: 999; border: 1px solid #ccc; overflow: hidden; } .big img { position: absolute; left: 0; top: 0; }
js(重点):
window.addEventListener('load',function(){ var preview_img = document.querySelector('.preview_img'); var mask = this.document.querySelector('.mask'); var big = this.document.querySelector('.big'); var bigImg = this.document.querySelector('.bigImg'); //鼠标经过 preview_img.addEventListener('mouseover',function(){ mask.style.display = 'block'; big.style.display = 'block'; }) //鼠标移出去 preview_img.addEventListener('mouseout',function(){ mask.style.display = 'none'; big.style.display = 'none'; }) //鼠标移动的时候 preview_img.addEventListener('mousemove',function(e){ //鼠标在盒子内的坐标 var x = e.pageX - this.offsetLeft; var y = e.pageY - this.offsetTop; //遮挡层移动的距离 var maskX = x - mask.offsetWidth/2; var maskY = y -mask.offsetHeight/2; //大图移动距离 //遮挡层的最大移动距离 var maskMaxX = preview_img.offsetWidth - mask.offsetWidth; var maskMaxY = preview_img.offsetHeight - mask.offsetHeight; //如果X坐标小于0 就让它停留在0 的位置 if (maskX <= 0) { maskX = 0; }else if (maskX >= maskMaxX) { maskX = maskMaxX; } //如果Y坐标小于0 就让它停留在0 的位置 if (maskY <= 0) { maskY = 0; }else if (maskY >= maskMaxY) { maskY = maskMaxY; } //遮挡层移动 mask.style.left = maskX + 'px'; mask.style.top = maskY + 'px'; //大图片最大移动距离 var bigMaxX = bigImg.offsetWidth - big.offsetWidth; var bigMaxY = bigImg.offsetHeight - big.offsetHeight; //大图片的移动距离 X Y // 大图片的移动距离 = 遮挡层移动距离 * 大图片最大移动距离 / 遮挡层的最大移动距离 var bigX = maskX * bigMaxX / maskMaxX; var bigY = maskY * bigMaxY / maskMaxY; //大图和小图(鼠标移动)方向相反 bigImg.style.left = -bigX + 'px'; bigImg.style.top = -bigY + 'px'; }) })
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)