0%
前言
JS实现淘宝商品放大镜效果
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; }
.cur { position: relative; width: 400px; height: 400px; background: url("img/fire-fox-logo.png"); background-size: 400px 400px; }
.slider { position: absolute; width: 100px; height: 100px; background: black; opacity: 50%; }
.enlarge { position: absolute; width: 400px; height: 400px; margin: 0 400px; background: url("img/fire-fox-logo.png"); background-size: 1600px 1600px; }
</style> </head> <body>
<div class="cur"> <div class="slider"></div> <div class="enlarge"></div> </div>
</body> </html> <script>
let cur = document.querySelector(".cur"); let slider = document.querySelector(".slider"); let enlarge = document.querySelector(".enlarge");
slider.onmousedown = function(event) {
let e = event||window.event;
let startX = e.offsetX; let startY = e.offsetY;
document.onmousemove = function(event1) {
let e1 = event1||window.event;
let l = e1.clientX - startX; let t = e1.clientY - startY;
if (e1.clientX - startX >= 0 && e1.clientX - startX <= 300 && e1.clientY - startY >=0 && e1.clientY - startY <= 300) {
slider.style.left = l + "px"; slider.style.top = t + "px";
enlarge.style.backgroundPosition= `-${l*4}px -${t*4}px`;
}
}
}
slider.onmouseup = function() { document.onmousemove = null; }
</script>
|
完成
参考文献
哔哩哔哩——web前端小清风