未封装的js放大镜特效

时间:2023-03-08 16:31:13

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js放大镜特效</title>
</head>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#main{
position: relative;
}
.smallimg{
width:300px;
height: 300px;
position: absolute;
top: 50px;
left: 50px;
}
.mark{
width:100px;
height:100px;
position: absolute;
z-index: 100;
top: 0;
background:rgba(0,0,0,.6);
display: none;
cursor: move;
}
.bigimg{
position: absolute;
top:50px;
left:400px;
width:300px;
height: 300px;
overflow: hidden;
display: none;
}
#img1{
width:300px;
height:300px;
display: block;
}
#img2{
width: 900px;
height: 900px;
display: block;
}
</style>
<body>
<div id="main">
<div class="smallimg">
<img src="img/1.jpg" id="img1"/>
<div class="mark">

</div>
</div>
<div class="bigimg">
<img src="img/1.jpg" id="img2"/>
</div>
</div>
</body>
<script type="text/javascript">
window.onload=function(){

if(!document.getElementsByClassName){
document.getElementsByClassName = function(className, element){
var children = (element || document).getElementsByTagName('*');
var elements = new Array();
for (var i=0; i<children.length; i++){
var child = children[i];
var classNames = child.className.split(' ');
for (var j=0; j<classNames.length; j++){
if (classNames[j] == className){
elements.push(child);
break;
}
}
}
return elements;
};
}

//以上代码有效解决IE7、8浏览器不支持document.getElementsByClassName的问题。

var smallimg=document.getElementsByClassName('smallimg')[0];
var bigimg=document.getElementsByClassName('bigimg')[0];
var mark=document.getElementsByClassName('mark')[0];
var img2=document.getElementById("img2");
smallimg.onmouseover=function(e){
bigimg.style.display="block";
mark.style.display="block";
show(e);
}
smallimg.onmousemove=function(e){
bigimg.style.display="block";
mark.style.display="block";
show(e);
}
smallimg.onmouseout=function(e){
bigimg.style.display="none";
mark.style.display="none";
}
function show(e){
var e=e||window.event;
var L=e.clientX-smallimg.offsetLeft-mark.offsetWidth/2; //小方块的中心点
var T=e.clientY-smallimg.offsetTop-mark.offsetHeight/2;
var minL=0;
var minT=0;
var maxL=smallimg.offsetWidth-mark.offsetWidth;  
var maxT=smallimg.offsetHeight-mark.offsetHeight; 
if(L<minL){    
L=0;
}else if(L>maxL){  //判断方块是否出边界
L=maxL;
}
if(T<minT){
T=0;
}else if(T>maxT){
T=maxT;
}
mark.style.left=L+'px'; //小方块移动
mark.style.top=T+'px';
img2.style.marginLeft=L*-3+'px';  //右边大图移动
img2.style.marginTop=T*-3+'px';
}
}
</script>
</html>

未封装的js放大镜特效