写在最前面:一定要注意设置样式的时候大图片和小图片的width,height是有比例关系的;
废话不多说,直接放效果图
image.png
关于tools.js的一堆废话,这是一个自己封装的函数
放代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
*{
margin: 0px;
padding: 0px;
}
.middle{
width: 400px;
height: 400px;
display: inline-block;
position: relative;
margin: 50px ;
}
.middle img{
width: 400px;
height: 400px;
}
.middle .sbox{
width: 200px;
height: 200px;
background: rgba(1, 1, 3, 0.5);
position: absolute;
top: 0;
left: 0;
display: none;
}
.bigbox{
width: 400px;
height: 400px;
overflow: hidden;
display: inline-block;
position: relative;
display: none;
}
.bigbox img{
width: 800px;
height: 800px;
position: absolute;
left: 0;
top: 0;
}
</style>
<body>
<div class="middle">
<div class="image">
<img src="images/3e87bfcd0f787b3ce12001faa7bd649a.jpg" alt="">
</div>
<div class="sbox"></div>
</div>
<div class="bigbox">
<img src="images/3e87bfcd0f787b3ce12001faa7bd649a.jpg" alt="" id="imgbig">
</div>
<script src="tools.js"></script>
<script>
window.onload = function(){
var middle_ = $(".middle")[0];
var sbox_ = $(".sbox")[0];
console.log(sbox_);
var bigbox = $(".bigbox")[0];
var img_ = $("#imgbig");
var middle_X = middle_.offsetLeft;//获取 middle 盒子距离有定位父元素的 left 值
var middle_Y = middle_.offsetTop;//获取 middle 盒子距离有定位父元素的 top 值
// console.log(middle_X,middle_Y);
var middle_width = middle_.offsetWidth;//获取 middle 盒子的宽度
var middle_height = middle_.offsetHeight;//获取 middle 盒子的高度
// console.log(middle_width)
middle_.onmouseenter = function(){//鼠标移入 middle 显示焦点小方块 和 放大方块
sbox_.style.display = "block";
// /console.log(sbox_.style.display);
bigbox.style.display = "inline-block";
}
middle_.onmouseleave = function(){//鼠标移出 middle 隐藏焦点小方块 和 放大方块
sbox_.style.display = "none";
// /console.log(sbox_.style.display);
bigbox.style.display = "none";
}
middle_.onmousemove = function(event){
var sbox_width = sbox_.offsetWidth;//由于焦点小方块是在鼠标移入middle之后才显示,所以得在鼠标移入以后才获取得到他的宽度
var sbox_height = sbox_.offsetHeight;//焦点小方块高度
var style_left = event.pageX - middle_X -sbox_width/2;//event.pageX鼠标在文档内的x值,这里相当于将焦点盒子向左上移动了sbox_width/2
var style_top = event.pageY - middle_Y -sbox_height/2;
if(style_left<=0){//判定左边界
style_left = 0 ;
}
if(style_left >= middle_width/2){//判定右边界
style_left = middle_width/2;
}
if(style_top<=0){//判定上边界
style_top = 0 ;
}
if(style_top >= middle_height/2){//判定下边界
style_top = middle_height/2 ;
}
sbox_.style.left = style_left + "px";//让小盒子随着鼠标移动
sbox_.style.top = style_top + "px";
img_.style.left = -middle_width/sbox_width * style_left + "px";//让图片随着小盒子移动 成比例 反方向
img_.style.top = -middle_height/sbox_height * style_top + "px";
// console.log( -middle_height/sbox_height)
}
}
</script>
</body>
</html>
我自认为注释比较清楚。。。。。。。。。。。。。。。。。。。。
网友评论