JavaScript实现放大镜效果
JavaScript实现放大镜效果
html:
<div id="left"> <div id="kuai"></div> <div id="cover"></div> </div> <div id="right"> <img id="img" src="img/800.jpg" alt=""> </div>
css:
<style> *{ margin: 0; padding: 0; } #left{ float: left; width: 400px; height: 400px; background: url('./img/400.jpg') no-repeat; position: relative; } #kuai{ width: 200px; height: 200px; background-color: white; opacity: 0.5; position: absolute; left: 0; top: 0; display: none; } #cover{ width: 400px; height: 400px; position: absolute; left: 0; top: 0; outline: 3px dashed red; } #right{ float: left; width: 400px; height: 400px; overflow: hidden; margin-left: 20px; position: relative; display: none; } #right img{ position: absolute; left: 0; top: 0; } </style>
javascript:
<script> window.onload = function(){ // 1.抓取元素 var left = document.querySelector('#left') var kuai = document.querySelector('#kuai') var cover = document.querySelector('#cover') var right = document.querySelector('#right') var img = document.querySelector('#img') console.log(left,kuai,cover,right,img) // 2.绑定事件 cover.onmousemove = function(ev){ kuai.style.display = "block"; right.style.display = "block"; var ev = window.event || ev; console.log(ev) var l = ev.layerX || ev.offsetX; var t = ev.layerY || ev.offsetY; // document.title = l + '|' + t; //块的坐标(把 相减的结果,给块去使用,作为块的坐标) var k_l = l - 100; var k_t = t - 100; if(k_l<=0){ k_l = 0; } if(k_l>=200){ k_l = 200; } if(k_t<=0){ k_t = 0; } if(k_t>=200){ k_t = 200; } document.title = k_l + '|' + k_t; // 设置块的坐标 kuai.style.left = k_l + "px"; kuai.style.top = k_t + "px"; var img_l = k_l * -2; var img_t = k_t * -2; // console.log(img_l + '|' + img_t) // 设置右侧区域中的图的坐标 img.style.left = img_l + "px"; img.style.top = img_t + "px"; } } </script>
还没有留言,还不快点抢沙发?