效果要求
1.鼠标移至图片上方,鼠标周围出现黄色的的正方形框,黄色矩形框会随着鼠标的移动而移动;
2.将黄色正方形框里的内容的长和宽均放大2.4倍,并在图片右边进行显示。
实现原理:
为对应的元素绑定 onmousemove
响应函数
使得鼠标在对应元素内移动时将需要的元素设置相应的display
属性
并通过数学计算,调整相应元素的 top
和 left
用 if判断 实现对放大镜区域限制
为对应的元素绑定 onmouseleave
响应函数
代码展示
html:
<!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>
<link rel="stylesheet" href="./index.css">
</head>
<body style="height: 2000px;">
<div class="wrapper">
<div class="product">
<img src="./img/350px.jpg" alt="">
<span class="yellow"></span>
</div>
<div class="grow"></div>
</div>
<script src="./index.js"></script>
</body>
</html>
css:
*{
margin: 0;
padding: 0;
}
.wrapper{
width: 1200px;
height: 800px;
margin: 0 auto;
}
.product{
position: relative;
width: 333px;
height: 333px;
float: left;
}
.product img{
display: block;
width: 333px;
height: 333px;
position: absolute;
z-index: 1;
}
.yellow{
width: 166.5px;
height: 166.5px;
display: block;
background-color: rgba(255, 255, 0, 0.4);
position: absolute;
z-index: 2;
display: none;
}
.grow{
position: absolute;
top: 0;
left: 500px;
width: 397.2px;
height: 397.2px;
background-color: rebeccapurple;
background: url(./img/800px.jpg) no-repeat;
display: none;
}
js:
//获取节点
var product = document.querySelector(".product")
var yellow = document.querySelector(".yellow")
var grow = document.querySelector(".grow")
//移出时候隐藏放大镜和效果图
product.onmouseleave = function(){
// 隐藏元素
yellow.style.display = "none"
grow.style.display = "none"
}
//绑定响应函数
product.onmousemove = function (e) {
// 显示元素
yellow.style.display = "block"
grow.style.display = "block"
//调整top值和left值
var top = e.pageY - yellow.offsetHeight / 2 - product.offsetTop
var left = e.pageX - yellow.offsetWidth / 2 - product.offsetLeft
//限制区域
if (top < 0) {
top = 0
} else if (top > 165) {
top = 165.5
}
if (left < 0) {
left = 0
} else if (left > 165) {
left = 165.5
}
// 改变定位位置
yellow.style.top = top + "px"
yellow.style.left = left + "px"
// 计算相应的比例
var ratioY = top / (product.offsetHeight - yellow.offsetHeight)
var ratioX = left / (product.offsetWidth - yellow.offsetWidth)
// 改变背景图片位置
grow.style.backgroundPositionY = (- ratioY * grow.offsetHeight) + "px"
grow.style.backgroundPositionX = (- ratioX * grow.offsetWidth) + "px"
}
效果展示:
放大镜效果