實現(xiàn)思路:主要分為三大塊,展示圖片帜羊、蒙版咒程、放大的圖片,鼠標進入時候圖片時候顯示蒙版和放大的圖片區(qū)域
1讼育、首先限制蒙版的 left 帐姻、top
2稠集、在右邊放大的框下面超出隱藏一張大圖片,蒙版移動時候大圖片按照(move移動的距離/move能夠移動的最大距離 = 大圖片移動的距離/大圖片能夠移動的距離)的比例進行移動饥瓷,不過注意此時大圖片是相對反方向移動的剥纷,所以在大圖片移動時候切記加上負號
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>放大鏡</title>
<style>
#small{
width: 300px;
height: 300px;
float: left;
margin: 50px;
position: relative;
cursor: move;
}
#move{
width: 100px;
height: 100px;
background: rgba(255,255,0,.5);
position: absolute;
left: 0;
top: 0;
display: none;
}
#small_img{
width: 300px;
height: 300px;
}
#big{
float: left;
width: 400px;
height: 400px;
overflow: hidden;
display: none;
position: relative;
}
#big_img{
width: 1000px;
height: 1000px;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div id="box">
<div id="small">
<img id="small_img" src="./img/2.jpg" alt="">
<div id="move"></div>
</div>
<div id="big">
<img id="big_img" src="./img/2.jpg" alt="">
</div>
<script>
var oSmall = document.getElementById("small");
var oMove = document.getElementById("move");
var oBig = document.getElementById("big");
var oBig_img = document.getElementById("big_img");
oSmall.onmouseenter = function () {
oMove.style.display = "block";
oBig.style.display = "block";
var pointMove = {
left:0,
top:0
}
oSmall.onmousemove = function(ev){
var ev = ev ||window.event;
//當鼠標移入開始移動的時候 計算move 的定位信息
//移動的值是 鼠標的距離-samll距離瀏覽器邊緣的距離 - move自身一半的距離
pointMove.left = ev.clientX - oSmall.offsetLeft - oMove.offsetWidth/2;
pointMove.top = ev.clientY - oSmall.offsetTop - oMove.offsetHeight/2;
// 判斷臨界值
if(pointMove.left <= 0){
pointMove.left =0;
}else if(pointMove.left >= oSmall.clientWidth - oMove.offsetWidth){
pointMove.left = oSmall.clientWidth - oMove.offsetWidth;
}
if(pointMove.top <= 0){
pointMove.top =0;
}else if(pointMove.top >= oSmall.clientHeight - oMove.offsetHeight){
pointMove.top = oSmall.clientHeight - oMove.offsetHeight;
}
//對move塊進行賦值操作
oMove.style.left = pointMove.left +"px";
oMove.style.top = pointMove.top +"px";
// 比例計算:
// move移動的距離/move能夠移動的最大距離 = 大圖片移動的距離/大圖片能夠移動的距離
var scaleX = pointMove.left / (oSmall.clientWidth - oMove.offsetWidth);
var scaleY = pointMove.top / (oSmall.clientHeight - oMove.offsetHeight);
// 計算大圖應該向移動的距離
oBig_img.style.left = - scaleX * (oBig_img.offsetWidth - oBig.clientWidth) + "px";
oBig_img.style.top = - scaleY * (oBig_img.offsetHeight - oBig.clientHeight) + "px";
}
}
oSmall.onmouseleave = function () {
oMove.style.display = "none";
oBig.style.display = "none";
}
</script>
</div>
</body>
</html>