<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title></title> <style type="text/css"> #div1 { width:300px; height:300px; position:relative; margin:30px auto 0px; } #div1 img{ width: 300px; } #div1 span { width:150px; height:150px; background:red; position:absolute; left:0px; top:0px; display:none; opacity:0.2; } .show { width:100%; height:100%; background:red; position:absolute; left:0px; top:0px; z-index:10px; opacity:0.1; } #div2 { width:300px; height:300px; position:relative; top: -300px; left: 300px; display:none; overflow:hidden; margin:0px auto 0px; } #img1 { position:absolute; } </style> </head> <body> <div> <!-- 图片 --> <img src="https://www.jb51.net/images/xiangqing.png" alt=""> <!-- 鼠标选中框 --> <span></span> <!-- 背景 --> <div></div> </div> <div> <!-- 放大后的图片 --> <img src="https://www.jb51.net/images/xiangqingda.png" /> </div> </body> <script> // 加载完成后显示 window.onload=function () { var oDiv=document.getElementById('div1'); var oShow=document.getElementsByClassName('show')[0]; var oSpan=document.getElementsByTagName('span')[0]; var oImg=document.getElementById('img1'); // parentNode获得父节点 oShow.onmouseover=function() { oSpan.style.display='block'; oImg.parentNode.style.display='block'; }; oShow.onmouseout=function() { oSpan.style.display=''; oImg.parentNode.style.display=''; }; // 放大器移动 oShow.onmousemove=function(ev) { // 解决浏览器兼容问题 var oEvent=ev||event; // 获得鼠标的位置 var x=oEvent.offsetX-oSpan.offsetWidth/2; var y=oEvent.offsetY-oSpan.offsetHeight/2; // console.log(oEvent.clientY); // console.log(oDiv.offsetTop); // console.log(oSpan.offsetHeight/2); // console.log(oEvent.clientY); if(x<0) { x=0; } else if(x>oShow.offsetWidth-oSpan.offsetWidth) { x=oShow.offsetWidth-oSpan.offsetWidth; } if(y<0) { y=0; } else if(y>oShow.offsetHeight-oSpan.offsetHeight) { y=oShow.offsetHeight-oSpan.offsetHeight; } // 给选中框定位 oSpan.style.left=x+'px'; oSpan.style.top=y+'px'; // 给放大器定位 var percentX=x/(oShow.offsetWidth-oSpan.offsetWidth); var percentY=y/(oShow.offsetHeight-oSpan.offsetHeight); var oImgparent=oImg.parentNode; oImg.style.left=-percentX*(oImg.offsetWidth-oImgparent.offsetWidth)+'px'; oImg.style.top=-percentY*(oImg.offsetHeight-oImgparent.offsetHeight)+'px'; }; }; </script> </html>
JS图片放大效果简单实现代码
内容版权声明:除非注明,否则皆为本站原创文章。