實現效果

實現代碼:
<!DOCTYPE html>
<html>
<head>
<title>購物圖片放大</title>
<meta charset="utf-8">
<style type="text/css">
*{
padding: 0;
margin: 0;
}
.box{
width: 200px;
height: 200px;
margin: 100px;
border: 1px solid #ccc;
position: relative;
}
.big{
width: 400px;
height: 400px;
position: absolute;
top: 0;
left: 360px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
.mask{
width: 80px;
height: 80px;
background-color: rgba(3,12,60,0.4);
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
.small{
position: relative;
}
.small img{
width: 200px;
height: 200px;
}
.big img{
height: 1000px;
width: 1000px;
}
img{
vertical-align: top;
}
</style>
</head>
<body>
<!-- 大圖片寬度/big框寬度 = small框寬度/mask框寬度,並且小照片寬度 = small框寬度,如BigImg = 1000, SmallImg = small = 200,big=400,那么mask = 80 -->
<div class="box">
<div class="small">
<img src="./resident.jpg" alt="small Image">
<div class="mask"></div>
</div>
<div class="big">
<img src="./resident.jpg" alt="Big Image">
</div>
</div>
<script type="text/javascript">
window.onload = function(){
// 鼠標放到小盒子上時,大盒子圖片同等比例移動
//技術點:onmouseenter==onmouseover 第一個不冒泡
//技術點:onmouseleave==onmouseout 第一個不冒泡
//步驟:
//1.鼠標放上去顯示盒子,移開隱藏盒子
//2.mask跟隨移動
//3.右側的大圖片,等比例移動
var box = document.getElementsByClassName("box")[0];
var small = box.firstElementChild || box.firstChild;
var big = box.children[1];
var mask = small.children[1];
var bigImg = big.children[0];
// 1.鼠標放上去顯示盒子,移開隱藏盒子(為小盒子綁定事件)
// 調用封裝好的方法,顯示元素
small.onmouseenter = function(){
show(mask);
show(big);
}
// 調用封裝好的方法,隱藏元素
small.onmouseleave = function(){
hide(mask);
hide(big);
}
// 2. mask跟隨鼠標移動
// 綁定事件是onmousemove,事件源是small,只要在小盒子上移動1px,mask也要跟隨移動
small.onmousemove = function(event){
// 想移動mask,需要知道鼠標在small中的位置,x作為mask的left值,y作為mask的top值
event = event || window.event;
// 獲取鼠標在整個頁面的位置
var pagex = event.pageX || scroll().left + event.clientX;
var pagey = event.pageY || scroll().top + event.clientY;
// 讓鼠標在mask的最中間,減去mask寬高的一半,x、y為mask的坐標
// console.log(pagex + " " + pagey);
var x = pagex - box.offsetLeft - mask.offsetWidth/2;
var y = pagey - box.offsetTop - mask.offsetHeight/2;
// 限制mask的范圍,left取值大於0,小於小盒子的寬減mask的寬
if(x<0){
x = 0;
}
if(x>small.offsetWidth - mask.offsetWidth){
x = small.offsetWidth - mask.offsetWidth;
}
if(y<0){
y = 0;
}
if(y>small.offsetHeight - mask.offsetHeight){
y = small.offsetHeight - mask.offsetHeight;
}
// 移動mask
// console.log("x:" + x + " y:" + y);
mask.style.left = x + "px";
mask.style.top = y + "px";
//3.右側的大圖片,等比例移動
// 大圖片/大盒子 = 小圖片/mask盒子
// 大圖片走的距離/mask走的距離 = (大圖片-大盒子)/(小圖片-mask)
//比例var times = (bigImg.offsetWidth-big.offsetWidth)/(small.offsetWidth-mask.offsetWidth);
//大圖片走的距離/mask盒子走的距離 = 大圖片/小圖片
var times = bigImg.offsetWidth/small.offsetWidth;
var _x = x * times;
var _y = y * times;
bigImg.style.marginLeft = -_x + "px";
bigImg.style.marginTop = -_y + "px";
}
}
// 顯示隱藏元素
function show(element){
element.style.display = "block";
}
function hide(element){
element.style.display = "none";
}
</script>
</body>
</html>
