功能介绍
这段代码实现了一个基本的图片缩放和局部放大效果。当鼠标悬停在小图上时,会出现一个黄色的透明框(mask),同时右侧会显示一个大图(big)。随着鼠标在小图上的移动,mask的位置也会变化,并且大图中相应部分的细节会被展示出来。当鼠标移出小图区域时,mask和大图都会隐藏
CSS部分
.box
类设置了一些基本的边距,用于整体布局.small
类定义了小图的尺寸和边框样式.small img
设置了小图的尺寸.small .mask
定义了透明框的样式,包括尺寸、背景颜色等。初始状态是display: none;
,意味着默认情况下它是不可见的.big
类设置了大图的样式,包括位置、尺寸和初始隐藏状态
javascript部分
window.onload
确保DOM完全加载后才执行脚本- 通过
querySelector
获取页面上的元素 - 使用事件监听器来响应用户的动作:
mouseover
事件使得当鼠标进入小图区域时,mask和大图变得可见mouseout
事件使得当鼠标离开小图区域时,mask和大图再次隐藏mousemove
事件处理了鼠标在小图区域内移动的情况,计算mask的位置,并更新大图中的细节位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
position: relative;
margin-top: 20px;
margin-left: 20px;
}
.small {
width: 300px;
height: 300px;
border: 1px solid black;
}
.small img {
display: block;
width: 300px;
height: 300px;
}
.small .mask {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
background-color: rgba(255, 255, 0, 0.4);
cursor: pointer;
}
.big {
display: none;
overflow: hidden;
position: absolute;
top: 0;
left: 320px;
width: 400px;
height: 400px;
border: 1px solid black;
}
.big img {
position: absolute;
top: 0;
left: 0;
width: 600px;
height: 600px;
}
</style>
</head>
<body>
<div class="box">
<div class="small">
<img src="images/4.jpg">
<div class="mask"></div>
</div>
<div class="big">
<img src="images/4.jpg">
</div>
</div>
<script>
window.onload = function () {
var box = document.querySelector('.box')
var small = document.querySelector('.small')
var mask = document.querySelector('.mask')
var big = document.querySelector('.big')
small.addEventListener('mouseover', function () {
mask.style.display = 'block'
big.style.display = 'block'
})
small.addEventListener('mouseout', function () {
mask.style.display = 'none'
big.style.display = 'none'
})
small.addEventListener('mousemove', function (e) {
var x = e.pageX - box.offsetLeft - mask.offsetWidth / 2
var y = e.pageY - box.offsetTop - mask.offsetHeight / 2
if (x < 0) {
x = 0
} else if (x > small.offsetHeight - mask.offsetHeight) {
x = small.offsetWidth - mask.offsetWidth
}
if (y < 0) {
y = 0
} else if (y > small.offsetWidth - mask.offsetWidth) {
y = small.offsetWidth - mask.offsetWidth
}
mask.style.left = x + 'px'
mask.style.top = y + 'px'
var bigImg = big.children[0]
bigImg.style.left = -x * big.offsetWidth / small.offsetWidth + 'px'
bigImg.style.top = -y * big.offsetHeight / small.offsetHeight + 'px'
})
}
</script>
</body>
</html>