内容
1.鼠标移至图片上方,鼠标周围出现黄色的的正方形框,黄色矩形框会随着鼠标的移动而移动;
2.将黄色正方形框里的内容的长和宽均放大2.4倍,并在图片右边进行显示。
实验原理
事件绑定鼠标移入显示隐藏
事件绑定鼠标移动时获取距窗口距离并赋值给黄方形实现跟随
同时计算大图片的移动距离=遮挡层移动距离*大图片最大移动距离/遮挡层最大移动距离
html
<!DOCTYPE html>
<html lang="zh-CN">
<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>demo9</title>
<link rel="stylesheet" href="./css/demo9.css">
</head>
<body>
<div class="box">
<img src="./img/img1.webp" alt="" class="small">
<div class="sq"></div>
<div class="big">
<img src="./img/img1.webp" alt="">
</div>
</div>
<script src="./js/demo9.js"></script>
</body>
</html>
css
<style>
*{
margin: 0;
padding: 0;
}
.box{
position: relative;
width: 350px;
height: 350px;
}
.sq{
position: absolute;
top: 0;
left: 0;
width: 150px;
height: 150px;
background-color: yellow;
opacity: 0.5;
border: 1px solid #333;
display: none;
}
.small{
width: 360px;
height: 360px;
}
.big{
position: absolute;
left: 360px;
top: 0px;
width: 360px;
height: 360px;
overflow: hidden;
display: none;
}
.big>img{
width: 864px;
height: 864px;
position: absolute;
top: 0;
left: 0;
}
</style>
js
<script>
window.addEventListener('load', function () {
var box = document.querySelector('.box');
var yy = document.querySelector('.sq');
var big = document.querySelector('.big');
box.addEventListener('mouseover', function () {
yy.style.display = 'block';
big.style.display = 'block';
})
box.addEventListener('mouseout', function () {
yy.style.display = 'none';
big.style.display = 'none';
})
box.addEventListener('mousemove', function (e) {
var x = e.pageX - box.offsetLeft;
var y = e.pageY - box.offsetTop;
var width = x - yy.offsetWidth / 2;
var height = y - yy.offsetHeight / 2;
if(width<=0){
width=0;
}else if(width>=box.offsetWidth-yy.offsetWidth){
width = 100;
}
if(height<=0){
height=0;
}else if(height >= box.offsetHeight - yy.offsetHeight) {
height = box.offsetHeight - yy.offsetHeight;
}
yy.style.left = width + 'px';
yy.style.top = height + 'px';
var bigimg = document.querySelector('.big>img');
// 大图片的移动距离=遮挡层移动距离*大图片最大移动距离/遮挡层最大移动距离
var bigx=width*(bigimg.offsetWidth-big.offsetWidth) / (box.offsetWidth - yy.offsetWidth);
var bigy=height*(bigimg.offsetHeight-big.offsetHeight) / (box.offsetHeight - yy.offsetHeight);
bigimg.style.left= -bigx+'px';
bigimg.style.top= -bigy+'px';
})
})
</script>
样式
放大镜效果