前端小应用:模拟电商网站的图片局部放大功能。我们直接上代码吧。如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>前端小应用:模拟电商网站的图片局部放大功能 | Web前端之家www.jiangweishan.com</title> <style type="text/css"> *{ margin: 0; padding: 0; } .box{ position: relative; width: 300px; height: 200px; background: url("/images/tt/google.jpg"); /*设置背景图尺寸大小*/ background-size: 300px 200px; } .slider{ position: absolute; width: 100px; height: 100px; background: black; /*设置透明度0~1,0是全透明。*/ opacity: 0.3; } .small{ position: absolute; width: 100px; height:100px; background: url('/images/tt/google.jpg'); top: 0px; right: -300px; background-size: 300px 200px; /*让元素放大,scale(3)指宽高同时放大3倍。*/ transform: scale(3); } </style> </head> <body> <div class="box"> <div class="slider"></div> <div class="small"></div> </div> </body> </html> <script type="text/javascript"> var slider = document.querySelector('.slider'); var small = document.querySelector('.small'); //鼠标按下 slider.onmousedown = function(event){ var startX = event.offsetX; var startY = event.offsetY; //鼠标移动 document.onmousemove = function (event1) { var l = event1.clientX-startX; var t = event1.clientY-startY; //将小滑块限制在大滑块内 if(l <= 0) l = 0; if(l >= 200) l = 200; if(t <= 0) t = 0; if(t >= 100) t = 100; slider.style.left = l+"px"; slider.style.top = t+"px"; //修改小图的背景图定位 small.style.backgroundPosition="-"+l+"px -"+t+"px"; } } //鼠标抬起时,将鼠标移动事件移除 document.onmouseup = function () { document.onmousemove = null; } </script>
大家试试吧,建议大家图的路径改成电商的图,会更明显点咯。
网友评论文明上网理性发言 已有0人参与
发表评论: