让我为大家带来一个关于放大镜的实现方法吧!
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title></title><style>* {margin: 0;padding: 0;}.box {margin: 150px;overflow: hidden;}.big {display: none;width: 400px;height: 400px;margin-left: 10px;overflow: hidden;position: relative;}.small {width: 400px;height: 400px;float: left;position: relative;}.shadow {display: none;position: absolute;top: 0;left: 0;width: 200px;height: 200px;background-color: #fff;opacity: 0.5;}.big img {position: absolute;left: 0;top: 0;}</style>
</head><body><!-- 一个大盒子 --><div class="box"><!-- 小图片的盒子 --><div class="small"><!-- 小图片 --><img style="width: 400px; height: 400px;" src="1.jpg" alt=""><!-- 阴影 --><span class="shadow"></span></div><!-- 大图片的盒子 --><div class="big"><!-- 大图片 相当于2倍图 --><img style="width: 800px; height: 800px;" src="2.jpg" alt=""></div></div>
</body>
<script>//获取boxvar box = document.querySelector(".box")//获取小图片盒子var small = document.querySelector(".small")//获取阴影var shadow = document.querySelector(".shadow")// console.log(shadow);//获取大图片盒子var big = document.querySelector(".big")//获取图片var img = document.querySelector(".big img")//给小图片盒子设置移入事件small.onmouseover = function () {//移入阴影盒子显示shadow.style.display = "block"//移入大图片盒子显示big.style.display = "block"}//小盒子移出事件small.onmouseout = function () {//移出阴影盒子隐藏shadow.style.display = "none"//移出大盒子隐藏big.style.display = "none"}//小盒子鼠标移动事件small.onmousemove = function (e) {//鼠标的距离 - 盒子距离浏览器的距离 - 盒子自身一半的距离 = 向左或者向上距离阴影盒子的距离var x = e.clientX - box.offsetLeft - shadow.offsetWidth / 2var y = e.clientY - box.offsetTop - shadow.offsetHeight / 2if (x < 0) {x = 0} else if (x > small.offsetWidth - shadow.offsetWidth) {x = small.offsetWidth - shadow.offsetWidth}if (y < 0) {y = 0} else if (y > small.offsetHeight - shadow.offsetHeight) {y = small.offsetHeight - shadow.offsetHeight}shadow.style.left = x + "px"shadow.style.top = y + "px"//因为图片是从右向左移,所以要是-的x和y,大图片比小的大2倍,乘于2img.style.left = -x * 2 + "px"img.style.top = -y * 2 + "px"}
</script>
</html>
感谢大家的阅读,如有不对的地方,可以向我提出,感谢大家!