JS图片放大效果简单实现代码
本文实例为大家分享了JS实现图片放大效果,供大家参考,具体内容如下
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8"/>
<title></title>
<styletype="text/css">
#div1{
width:300px;
height:300px;
position:relative;
margin:30pxauto0px;
}
#div1img{
width:300px;
}
#div1span{
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:0pxauto0px;
}
#img1{
position:absolute;
}
</style>
</head>
<body>
<divid="div1">
<!--图片-->
<imgsrc="images/xiangqing.png"alt="">
<!--鼠标选中框-->
<span></span>
<!--背景-->
<divclass="show"></div>
</div>
<divid="div2">
<!--放大后的图片-->
<imgid="img1"src="images/xiangqingda.png"/>
</div>
</body>
<script>
//加载完成后显示
window.onload=function(){
varoDiv=document.getElementById('div1');
varoShow=document.getElementsByClassName('show')[0];
varoSpan=document.getElementsByTagName('span')[0];
varoImg=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){
//解决浏览器兼容问题
varoEvent=ev||event;
//获得鼠标的位置
varx=oEvent.offsetX-oSpan.offsetWidth/2;
vary=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;
}elseif(x>oShow.offsetWidth-oSpan.offsetWidth){
x=oShow.offsetWidth-oSpan.offsetWidth;
}if(y<0){
y=0;
}elseif(y>oShow.offsetHeight-oSpan.offsetHeight){
y=oShow.offsetHeight-oSpan.offsetHeight;
}
//给选中框定位
oSpan.style.left=x+'px';
oSpan.style.top=y+'px';
//给放大器定位
varpercentX=x/(oShow.offsetWidth-oSpan.offsetWidth);
varpercentY=y/(oShow.offsetHeight-oSpan.offsetHeight);
varoImgparent=oImg.parentNode;
oImg.style.left=-percentX*(oImg.offsetWidth-oImgparent.offsetWidth)+'px';
oImg.style.top=-percentY*(oImg.offsetHeight-oImgparent.offsetHeight)+'px';
};
};
</script>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。