<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>放大鏡</title> <style> *{ margin:0px; padding:0px; } #box{ width:430px; height:430px; ...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>放大鏡</title>
<style>
*{
margin:0px;
padding:0px;
}
#box{
width:430px;
height:430px;
margin:100px;
margin-left:17%;
position:relative;//這裡使用相對定位,好讓其他的元素能依靠這個元素定位
}
#move{
background-color:green;
width:220px;
height:220px;
position:absolute;
left:0px;
top:0px;
display:none;//先讓他隱藏,用js使其顯示
}
#bimg{
width:430px;
height:430px;
overflow:hidden;
position:absolute;
top:0px;
left:450px;
display:none;//先讓他隱藏,用js使其顯示
}
#bimg img{
width:800px;
height:800px;
position:absolute;
top:0px;
left:0px;
}
</style>
</head>
<body onload="bigimg()">
<div id="box">
<img src="img/4.jpg" alt="#">
<div id="move"></div>
<div id="bimg">
<img id="b_bimg" src="img/4.jpg" alt="#">
</div>
</div>
<script>
function bigimg(){
var bbox = document.getElementById("box");
var bmove = document.getElementById("move");
var bbimg = document.getElementById("bimg");
var b_bimg = document.getElementById("b_bimg");
bbox.onmouseover = function(){//滑鼠移動到box上顯示大圖片和選框
bbimg.style.display = "block";
bmove.style.display="block";
}
bbox.onmouseout = function(){//滑鼠移開box不顯示大圖片和選框
bbimg.style.display = "none";
bmove.style.display="none";
}
bbox.onmousemove = function(e){//獲取滑鼠位置
var x = e.clientX;//滑鼠相對於視口的位置
var y = e.clientY;
var t = bbox.offsetTop;//box相對於視口的位置
var l = bbox.offsetLeft;
var _left = x - l - bmove.offsetWidth/2;//計算move的位置
var _top = y - t -bmove.offsetHeight/2;
if(_top<=0)//滑到box的最頂部
_top = 0;
else if(_top>=bbox.offsetHeight-bmove.offsetHeight)//滑到box的最底部
_top = bbox.offsetHeight-bmove.offsetHeight ;
if(_left<=0)//滑到box的最左邊
_left=0;
else if(_left>=bbox.offsetWidth-bmove.offsetWidth)//滑到box的最右邊
_left=bbox.offsetWidth-bmove.offsetWidth ;
bmove.style.top = _top +"px";//設置move的位置
bmove.style.left = _left + "px";
var w = _left/(bbox.offsetWidth-bmove.offsetWidth);//計算移動的比例
var h = _top/(bbox.offsetHeight-bmove.offsetHeight);
var b_bimg_top = (b_bimg.offsetHeight-bbimg.offsetHeight)*h;//計算大圖的位置
var b_bimg_left = (b_bimg.offsetWidth-bbimg.offsetWidth)*w;
b_bimg.style.top = -b_bimg_top + "px";//設置大圖的位置信息
b_bimg.style.left = -b_bimg_left + "px";
}
}
</script>
</body>
</html>
黑色箭頭:
1 2 |
var x = e.clientX; //滑鼠相對於視口的位置
var y = e.clientY;
|
紅色箭頭:
1 2 |
var t = bbox.offsetTop; //box相對於視口的位置
var l = bbox.offsetLeft;
|
橙色箭頭:
1 2 |
var _left = x - l - bmove.offsetWidth/2; //計算move的位置
var _top = y - t -bmove.offsetHeight/2;
|
2、bimg塊的計算
利用move塊在可移動範圍內的比例來設置大圖的位置
move塊的移動範圍:
1 |
bbox.offsetWidth-bmove.offsetWidth
|
move塊現在的坐標占可移動範圍的比例:
1 2 |
var w = _left/(bbox.offsetWidth-bmove.offsetWidth); //計算移動的比例
var h = _top/(bbox.offsetHeight-bmove.offsetHeight);
|
bimg的移動範圍:
1 |
b_bimg.offsetHeight-bbimg.offsetHeight
|
bimg的位置:
1 2 |
var b_bimg_top = (b_bimg.offsetHeight-bbimg.offsetHeight)*h; //計算大圖的位置
var b_bimg_left = (b_bimg.offsetWidth-bbimg.offsetWidth)*w;
|