用js做一个放大镜的小例子
css样式:
body{
margin: 0;
}
.box{
width: 900px;
margin:40px auto;
height: 400px;
}
.top{
width: 900px;
margin:100px auto 0 auto;
box-shadow: 3px 3px 5px red;
background: blue;
text-align: center;
color: #fff;
font:bold 30px/60px "黑体";
}
.small,.big{
float: left;
width: 430px;
height: 430px;
border: 1px solid #ccc;
position: relative;
}
img{
vertical-align: top;
}
.big{
overflow: hidden;
border: 0;
}
.big img{
position: absolute;
left: 0;
top: 0;
}
.small{
margin-right: 20px;
}
.cross{
width: 200px;
height: 200px;
background: url(img/sqr.png);
position: absolute;
left: 0;
top: 0;
display: none;
cursor: move;
}
.big{
display:none;
}
html结构:
<div class="box">
<div class="small">
<img src="img/small7.jpg" alt="">
<div class="cross"></div>
</div>
<div class="big">
<img src="img/big7.jpg" alt="">
</div>
上述中自己添加三张图片 big7.jpg small7.jpg sqr.png
js代码:
var box = document.querySelector('.box');
var small = document.querySelector('.box .small');
var cross = document.querySelector('.box .cross');
var big = document.querySelector('.box .big');
var img = document.querySelector('.box .big img');
small.onmouseover = function(e){
e = e || event;
big.style.display = "block";
cross.style.display = "block";
var cl = cross.offsetWidth/2;
var ct = cross.offsetHeight/2;
cross.onmousemove = function(e){
e = e || event;
var l = e.clientX - 175 - cl;
var t = e.clientY - 40 - ct;
if(l <= 0){
l = 0;
}else if(l >= small.offsetWidth - cross.offsetWidth){
l = small.offsetWidth - cross.offsetWidth;
}
if(t <= 0){
t = 0;
}else if(t >= small.offsetHeight - cross.offsetHeight){
t = small.offsetHeight - cross.offsetHeight;
}
cross.style.cssText = 'left:'+l+'px;top:'+t+'px;display:block';
var bl = - (l/(small.offsetWidth - cross.offsetWidth))*big.offsetWidth;
var bt = - (t/(small.offsetHeight - cross.offsetHeight))*big.offsetHeight;
img.style.cssText = 'left:'+bl+'px;top:'+bt+'px;display:block';
}
}