一、要求
1.鼠标移至图片上方,鼠标周围出现黄色的的正方形框,黄色矩形框会随着鼠标的移动而移动;
2将黄色正方形框里的内容的长和宽均放大2.4倍,并在图片右边进行显示。
二、实验原理
- 首先通过html,css进行网页布局,在通过其js实现效果展示
- 首先通过鼠标事件完成,左边小图鼠标进入和移出时,黄色和大图片的显示和消失,再通过定位的方式,让黄色阴影跟着鼠标移动
- 大图的运动依靠的是定位,因为大图是小图的2.4倍,且运动相反,即相对定位*-2.4即可
三、实验效果图
放大镜效果
四、主要代码展现
<!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>
*{
margin: 0;
padding: 0;
}
.box{
margin: 400px;
clear: left;
}
.small{
position: relative;
float: left;
}
.shade{
width: 100px;
height: 100px;
background-color:yellow ;
position: absolute;
top: 0;
left: 0 ;
opacity: 50%;
display: none;
}
.big{
width: 400px;
height: 400px;
overflow: hidden;
margin-left: 40px;
display: none;
float: left;
position: relative;
}
.big img{
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box">
<div class="small">
<img src="./O1CN01fB5t3K24bNFkCWxho_!!0-item_pic.jpg" width="400px" height="400px">
<span class="shade"></span>
</div>
<div class="big">
<img src="./O1CN01fB5t3K24bNFkCWxho_!!0-item_pic.jpg" width="960px" height="960px">
</div>
</div>
<script>
//左边的小盒子
var osmall = document.querySelector('.small')
var oshade = document.querySelector('.shade')
var obig = document.querySelector('.big')
var obox = document.querySelector(".box")
//当鼠标移入的时候阴影和大盒子全部显示
osmall.onmouseover= function(){
oshade.style.display = "block"
obig.style.display = "block"
}
//移出时消失
osmall.onmouseout= function(){
oshade.style.display = "none"
obig.style.display = "none"
}
//鼠标移动时,黄色阴影跟着运动
osmall.onmousemove = function(e){
var Width = e.clientX - obox.offsetLeft - oshade.offsetWidth/2
var Height = e.clientY - obox.offsetTop - oshade.offsetHeight/2
//让黄色的阴影在小的图片区域里面
//设置其宽度
if(Width < 0){
Width = 0
}else if(Width >= osmall.offsetWidth - oshade.offsetWidth){
Width = osmall.offsetWidth-oshade.offsetWidth
}
//设置其高度
if(Height < 0){
Height = 0
}else if(Height >= osmall.offsetHeight - oshade.offsetHeight){
Height = osmall.offsetHeight- oshade.offsetHeight
}
//更改样式
oshade.style.left = Width + 'px'
oshade.style.top = Height + 'px'
//大图片效果设置
var obigImg = document.querySelector('.big>img')
obigImg.style.top = Height * -2.4 +'px'
obigImg.style.left = Width*-2.4 + 'px'
}
</script>
</body>
</html>