用原生js,实现放大镜效果
css
<style> *{ margin:0; padding:0; } #box{ width:350px; height:350px; border:1px solid #000; margin:100px; position:relative; } #big{ width:400px; height:400px; border:1px solid #000; position:absolute; top : 0; left : 360px; overflow:hidden; display:none; } #mask{ width:175px; height:175px; background:pink; opacity:0.3; position:absolute; top:0; left:0; cursor:move; display:none } #small{ position:relative; } #bigImg{ position:absolute; left:0; top:0; } </style>
html
<div id="box"> <div id="small"> <img src="images/iphone.jpg" alt="" id="smallImg"/> <div id="mask"></div> </div> <div id="big"> <img src="images/iphone_big.jpg" alt="" id="bigImg"/> </div> </div>
js
<script> var small = document.getElementById("small"); var smallImg = document.getElementById("smallImg"); var mask = document.getElementById("mask"); var big = document.getElementById("big"); var bigImg = document.getElementById("bigImg"); var box = document.getElementById("box"); small.onmouseover = function(){ mask.style.display = "block"; big.style.display = "block"; } small.onmouseout = function(){ mask.style.display = "none"; big.style.display = "none"; } small.onmousemove = function(e){ var e = e || event; var x = e.pageX - box.offsetLeft - mask.offsetWidth / 2 ; var y = e.pageY - box.offsetTop - mask.offsetHeight / 2 ; var maxL = box.offsetWidth - mask.offsetWidth; var maxT = box.offsetHeight - mask.offsetHeight; x = x < 0 ? 0 : x > maxL ? maxL : x; y = y < 0 ? 0 : y > maxT ? maxT : y; mask.style.left = x + "px"; mask.style.top = y + "px"; var bigL = x * (bigImg.offsetWidth - big.offsetWidth) / (box.offsetWidth - mask.offsetWidth); var bigT = y * (bigImg.offsetHeight - big.offsetHeight) / (box.offsetHeight - mask.offsetHeight); bigImg.style.left = - bigL + "px"; bigImg.style.top = - bigT + "px"; } </script>