html和css
<body>
<div id="div1">
<div id="mark">
</div>
<img src="timg.jpg" >
</div>
<div id="div2">
<img src="timg.jpg" id="img">
</div>
</body>
*{margin: 0;padding: 0;}
#div1{width: 400px;height: 300px; position:absolute;left: 320px;top: 320px;}
#div1 img{width: 100%;height: 100%;}
#mark{height: 100px;width: 100px;opacity: 0.5;background-color: #808080;display: none;position: absolute;}
#div2{height: 200px;width: 200px;border: 1px #000000 solid;overflow: hidden;margin: 100px;display: none;}
#div2 img{width: 800px;height: 600px;position: relative;}
JS代码
window.onload=function(){
var oDiv1=document.getElementById("div1");
var oMark=document.getElementById("mark");
var oDiv2=document.getElementById("div2");
var oImg=document.getElementById("img");
oDiv1.onmouseover=function(){
oMark.style.display="block";
oDiv2.style.display="block";
}
oDiv1.onmouseout=function(){
oMark.style.display="none";
oDiv2.style.display="none"
}
oDiv1.onmousemove=function(ev){
var e=ev||window.event;
var l=e.clientX-oDiv1.offsetLeft-50;
var t=e.clientY-oDiv1.offsetTop-50;
if(l<=0){
l=0;
}
if(l>=300){
l=300;
}
if(t<=0){
t=0;
}
if(t>=200){
t=200;
}
oMark.style.left=l+"px";
oMark.style.top=t+"px";
oImg.style.left=-2*l+"px";
oImg.style.top=-2*t+"px";
}
}
timg.jpg
上述放大镜功能可以将图片放大两倍。为什么l和t要减去50个像素,因为mark跟随鼠标移动时,要使鼠标保持在mark的中心点。l和t判断>=时,需要div1 的宽高减去mark的宽高。
版权声明:本文为weixin_42303695原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。