放大镜
< !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>放大镜< /title>
< style>
/* 左侧样式 /
.left{
width: 300px;
height: 300px;
background-image: url(“77.jpg”);
background-size: 100% 100%;
position: relative;
float: left;
}
.left_a{
width: 150px;
height: 150px;
background-color: forestgreen;
opacity: .5;
position: absolute;
display: none;
}
/ 右侧样式 /
.right{
width: 350px;
height:350px;
background-color: purple;
float: left;
overflow: hidden;
position: relative;
display: none;
}
.right img{
width: 700px;
height: 700px;
position: absolute;
/ display: none; */
}
< /style>
< /head>
< body>
< div class=“left”>
< div class=“left_a”>< /div>
< /div>
< div class=“right”>
< img src=“77.jpg” alt="">
< /div>
< /body>
< script>
//获取元素
var dLeft = document.getElementsByClassName(“left”)[0];
var dLeftA = document.getElementsByClassName(“left_a”)[0];
var dRight = document.getElementsByClassName(“right”)[0];
var img = document.querySelector(".right img");
// 1.鼠标移入 left_a和right要显示
// 2.鼠标移动 产生对应的变化
// 3.鼠标移出 left_a和right要隐藏
//鼠标移入 left_a和right要显示
dLeft.onmouseenter = function(){
dLeftA.style.display = ‘block’;
dRight.style.display = ‘block’;
}
//鼠标移动
//e:事件对象,包含了该事件所有的相关信息
dLeft.onmousemove = function(e){
//兼容写法
// window.event;后边这个是兼容IE67,8
// var e = e || window.event;
// 1.left_a跟随指针
var x = e.clientX - this.offsetLeft-75;
var y = e.clientY - this.offsetTop-75;
x = (x < 0) ? 0 : x;
x = (x > 150) ? 150 : x;
y = (y < 0) ? 0 : y;
y = (y > 150) ? 150 : y;
dLeftA.style.left = x + ‘px’;
dLeftA.style.top = y + ‘px’;
// 2.大图对应变化 x1/w1 = -x2/w2;
var x2 = -1 * x * 700 / 300;
var y2 = -1 * y * 700 / 300;
img.style.left = x2 + ‘px’;
img.style.top = y2 + ‘px’;
}
//鼠标移出 left_a和right要隐藏
dLeft.onmouseleave = function(){
dLeftA.style.display = ‘none’;
dRight.style.display = ‘none’;
}
< /script>
< /html>