效果:當滑鼠在小圖上方時,在右邊顯示放大的圖檔
思路:
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 >
<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>
具體效果可見:放大鏡