效果示例:
思想过程:
在一个大盒子里放一个图片,一个半透明的黄色遮罩层(带有绝对定位才可以移动),一个放大过后的图片,采取绝对定位固定到图片的一侧
html+css的片段:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.a1 {
position: relative;
width: 300px;
height: 300px;
cursor: move;
}
.a1>img{
width: 100%;
height: 100%;
}
.a1box {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
background-color: #FEDE4F; //设置颜色
opacity: 0.5; // 设置为半透明
}
.big {
display: none;
position: absolute;
left: 310px;
top: 0;
width: 600px;
height: 600px;
overflow: hidden;
}
.big>img {
position: absolute;
top: 0;
left: 0;
width: 200%;
height: 200%;
}
</style>
<script src="try.js"></script> //引入js代码片段
</head>
<body>
<div class="a1">
<img src="../../../html+css/images/yzfc.jpg" alt="">
<div class="a1box"></div>
<div class="big">
<img src="../../../html+css/images/yzfc.jpg" alt="" class="bigimg">
</div>
</div>
</body>
</html>
javascript的片段::
window.addEventListener('load',function() {
//获取各个元素
var a1 = document.querySelector('.a1');
var a1box = document.querySelector('.a1box');
var big = document.querySelector('.big')
var bigimg = document.querySelector('.bigimg')
// 1.鼠标经过两个图片显示出来哦
a1.addEventListener('mouseover',function() {
a1box.style.display = 'block';
big.style.display = 'block';
})
// 2.鼠标离开,两个图片的display改为none,隐藏
a1.addEventListener('mouseout',function() {
a1box.style.display = 'none';
big.style.display = 'none';
})
// 3.当鼠标在其中移动时的相关联的代码及解释
a1.addEventListener('mousemove',function(e){
var x = e.pageX -a1.offsetLeft; //获取 鼠标在盒子内的x坐标
var y = e.pageY - a1.offsetTop; // 获取 鼠标在盒子内的x坐标
x = x - a1box.offsetWidth/2; // 使得鼠标在盒子的中间
y = y - a1box.offsetWidth/2; // 使得鼠标在盒子的中间
xmax = a1.offsetWidth - a1box.offsetWidth; //算出盒子在x方向的最大移动距离
ymax = a1.offsetHeight - a1box.offsetHeight; // 算出设置盒子在y方向最大的移动距离
// 判断鼠标是否离开盒子,防止盒子跟着鼠标离开父容器
if(x<=0) {
x=0;
}
if(y<=0) {
y=0;
}
if(x>=xmax) {
x = xmax +'px';
}
if(y>=xmax) {
y = ymax+ 'px';
}
a1box.style.left = x+'px'; //设置盒子的 x坐标
a1box.style.top = y+'px'; // 设置盒子的 y坐标
//大图片移动距离= 遮挡层移动距离*大图片最大移动距离/遮挡层的最大移动距离
var bigimgx = bigimg.offsetWidth - big.offsetWidth; //获取大图片x方向上的最大移动距离
var bigimgy = bigimg.offsetHeight - big.offsetHeight; //获取大图片y方向上的最大移动距离
bigimg.style.left = -x * bigimgx / xmax +'px' //根据公式求出 大图片x方向应该移动的距离
bigimg.style.top = -y * bigimgx / ymax +'px' // 根据公式求出 大图片y方向应该移动的距离
})
})
本图为代码示例的图,可搬走。