HTML:
放大镜效果
CSS:
* { margin: 0; padding: 0;} body { background: #000;} img { vertical-align: bottom;} #box { position: relative; margin: 10px; padding: 10px; width: 260px; background: #fff;}#large-box { display: none; position: absolute; top: 0; left: 290px; width: 260px; height: 260px; overflow: hidden;}#large-img { position: absolute; width: 520px; height: 520px;}#middle-box { position: relative;}#middle-img { width: 100%;}#shadow { display: none; position: absolute; left: 0; top: 0; width: 130px; height: 130px; background: rgba(255, 0, 0, .4); cursor: move;}#small-box { margin-top: 10px; overflow: hidden;}#small-box img{ float: left; width: 63px; border: 1px solid #fff;}#small-box .active { border-color: red;}
js:
function $(id) { return document.getElementById(id);} var oBox = $('box');var oSmallBox = $('small-box');var aSmallImg = Array.from(oSmallBox.children);var oMiddleBox = $('middle-box');var oMiddleImg = $('middle-img');console.log(oMiddleImg);var oLargeBox = $('large-box');var oLargeImg = $('large-img');var oShadow = $('shadow'); // 给缩略图添加鼠标进入事件aSmallImg.forEach( v => { v.onmouseover = function () { // 先去掉所有的class名 aSmallImg.forEach(v => v.className = ''); // 当前img添加class this.className = 'active'; // 改变中型图片的地址 oMiddleImg.src = this.src; // 改变大型图片的地址 oLargeImg.src = this.src; };}); // 遮罩层最大的left和top值var maxL = 0;var maxT = 0;// 大图片最大的left和top值var maxLargeImgL = 0;var maxLargeImgT = 0; // 鼠标进入middle-boxoMiddleBox.onmouseover = function () { // 显示遮罩层 oShadow.style.display = 'block'; // 显示右侧的盒子 oLargeBox.style.display = 'block'; // 获取最大的left和top值 maxL = oMiddleBox.offsetWidth - oShadow.offsetWidth; maxT = oMiddleBox.offsetHeight - oShadow.offsetHeight; maxLargeImgL = oLargeImg.offsetWidth - oLargeBox.offsetWidth; maxLargeImgT = oLargeImg.offsetHeight - oLargeBox.offsetHeight;}; // 鼠标离开middle-boxoMiddleBox.onmouseout = function () { // 显示遮罩层 oShadow.style.display = 'none'; // 显示右侧的盒子 oLargeBox.style.display = 'none';}; // 给middle-box添加移动事件oMiddleBox.onmousemove = function (ev) { var e = ev || window.event; var iL = e.clientX - oShadow.offsetWidth / 2 - oMiddleBox.offsetLeft - oBox.offsetLeft; var iT = e.clientY - oShadow.offsetHeight / 2 - oMiddleBox.offsetTop - oBox.offsetTop; // 限定左侧 if(iL < 0) { iL = 0; } // 限定上侧 if(iT < 0) { iT = 0; } // 限定右侧 if(iL > maxL) { iL = maxL; } // 限定下侧 if(iT > maxT) { iT = maxT; } oShadow.style.left = iL + 'px'; oShadow.style.top = iT + 'px'; // 让大图移动 oLargeImg.style.left = - iL * maxLargeImgL / maxL + 'px'; oLargeImg.style.top = - iT * maxLargeImgT / maxT + 'px';};
图片更换成自己的路径即可