效果:当鼠标在小图上方时,在右边显示放大的图片
思路:
css布局:在大盒子box里,放入两个盒子small(放小图)和big(放大图),并在small里放一个用来显示放大区域的半透明盒子mask;然后利用定位布局mask和big的位置
js:使用onmouseover/onmouseout事件显示/隐藏big盒子和mask;使用onmousemove事件设定mask盒子位置和显示big盒子里的放大图片
关键知识:position定位,onmousemove,offsetLeft,offsetTop,offsetHeight,offsetWidth,事件对象event及其属性clientX/clientY
具体代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>放大镜</title>
<style>
.box {
width: 350px;
height: 350px;
margin: 100px 200px;
border: 1px solid #ccc;
position: relative;
}
.small {
position: relative;
}
.big {
width: 450px;
height: 450px;
position: absolute;
top: 0;
left: 360px;
overflow: hidden;
border: 1px solid #ccc;
display: none;
}
.mask {
width: 100px;
height: 100px;
background: rgba(255,255,0,0.3);
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
.big img{
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="small">
<img src="images/001.jpg" alt="picture"/>
<div class="mask"></div>
</div>
<div class="big">
<img src="images/0001.jpg" alt="picture"/>
</div>
</div>
</body>
<script>
var box = document.getElementById('box');
var small = box.children[0];//放小图的盒子
var big = box.children[1];//放大图的盒子
var mask = small.children[1];//半透明鼠标移动跟随盒子
var bigImage = big.children[0];//大图片
// console.log(box,small,big,mask);
small.onmouseover = function(event){
big.style.display = 'block';
mask.style.display = 'block';
}
small.onmouseout = function(){
big.style.display = 'none';
mask.style.display = 'none';
}
//移动事件,注意mask的定位相对的是samll
small.onmousemove = function(event){
var event = event || window.event;//事件对象
// console.log(this.offsetLeft);//0,注意offsetLeft返回距离是一个带有定位的父级的左侧距离
var x = event.clientX-this.offsetParent.offsetLeft-mask.offsetWidth/2;//此处不能用small的offsetLeft,用box的offsetLeft
var y = event.clientY-this.offsetParent.offsetTop-mask.offsetHeight/2;
//限制半透明盒子出界
if(x < 0){
x = 0;
}else if(x > small.offsetWidth - mask.offsetWidth){
x = small.offsetWidth - mask.offsetWidth;
}
if( y < 0){
y = 0;
}else if( y > small.offsetHeight - mask.offsetHeight){
y = small.offsetHeight - mask.offsetHeight;
}
mask.style.left = x + "px";
mask.style.top = y +"px";
//大图片放大
bigImage.style.left = -x*big.offsetWidth/small.offsetWidth + 'px';
bigImage.style.top = -y*big.offsetHeight/small.offsetHeight + 'px';
//big.offsetWidth/small.offsetWidth是放大倍数
//因为小图鼠标下移,大图上移,故用负数
}
</script>
</html>
具体效果可见:放大镜