效果
实现
复制粘贴,修改图片路径即可使用
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>商品图片放大镜</title></head><style>body {margin: 0;padding: 0;}#app {padding: 10px;position: relative;}/** 默认图片*/.img-box {position: relative;left: 10px;top: 150px;width: 300px;height: 300px;text-align: center;border: 1px solid #83b4ff;border-radius: 4px;overflow: hidden;cursor: zoom-in;}.img1 {width: 100%;height: 100%;}.img-select {width: 100px;height: 100px;position: absolute;left: 0;top: 0;background: #00ff6633;border-radius: 4px;display: none;}/** 临时放大图片*/.img-temp-box {position: absolute;left: 0;top: 0;width: 400px;height: 400px;display: none;overflow: hidden;}.img2 {width: 200%;height: 200%;position: absolute;left: 0;top: 0;}</style><body><div id="app"><div class="img-box"><img src="image/2.jpeg" class="img1" /><div class="img-select"></div></div></div><!-- 一般放置最外边--><div class="img-temp-box"><img src="" class="img2" /></div></body><script>/*** @author yyq* @blogger myf*/var imgBox = document.querySelector('.img-box');var imgSelect = document.querySelector('.img-select');var imgTempBox = document.querySelector('.img-temp-box');var img1 = document.querySelector('.img1');var img2 = document.querySelector('.img2');// 鼠标移入imgBox.onmouseenter = function() {imgSelect.style.display = 'block';imgTempBox.style.display = 'block';var img = getElementOffset(imgBox);imgTempBox.style.left = (img.left + 400) + "px";imgTempBox.style.top = (img.top - 50) + "px";img2.src = img1.src;console.log("移入")}// 鼠标移除imgBox.onmouseleave = function() {imgSelect.style.display = 'none';imgTempBox.style.display = 'none';console.log("移除")}// 鼠标放上imgBox.onmousemove = function() {var img = getElementOffset(imgBox);var x = event.clientX - img.left;var y = event.clientY - img.top;console.log("xy轴:", x, '-----', y);var imgSelectX = x - imgSelect.offsetWidth / 2var imgSelectY = y - imgSelect.offsetHeight / 2if(imgSelectX < 0) {imgSelectX = 0;} else if(imgSelectX > imgBox.offsetWidth - imgSelect.offsetWidth) {imgSelectX = imgBox.offsetWidth - imgSelect.offsetWidth}if(imgSelectY < 0) {imgSelectY = 0;} else if(imgSelectY > imgBox.offsetHeight - imgSelect.offsetHeight) {imgSelectY = imgBox.offsetHeight - imgSelect.offsetHeight}// 小图里的小框imgSelect.style.left = imgSelectX + 'px';imgSelect.style.top = imgSelectY + 'px';var b = (img2.offsetHeight - imgTempBox.offsetHeight) / (imgBox.offsetHeight - imgSelect.offsetHeight)// 临时框里的大图片img2.style.left = -imgSelectX * b + "px"img2.style.top = -imgSelectY * b + "px"}/*** 返回元素距离浏览器边框的位置(防止元素位置被父级限制)* @param {Object} element*/function getElementOffset(element) { var left = element.offsetLeft; // 当前元素左边距var top = element.offsetTop; // 当前元素上边距var parent = element.offsetParent; // 当前元素的父级元素while(parent !== null) { left += parent.offsetLeft; // 累加左边距top += parent.offsetTop; // 累加上边距parent = parent.offsetParent; // 依次获取父元素}return {'left': left,'top': top}; }</script></html>