1、html代码
<div class="box">
<div class="fdj"></div>
</div>
<div class="show">
<img src="img/img.png" height="2000" width="2000" alt=""/>
</div>
2、css样式
* {
margin: 0;
padding: 0
}
body {
height: 2000px;
}
.box {
width: 400px;
height: 400px;
background-image: url("img/img.png");
position: relative;
float: left;
}
.fdj {
position: absolute;
background-color: rgba(200, 100, 100, 0.5);
height: 100px;
width: 100px;
display: none;
}
.show {
height: 400px;
width: 400px;
float: left;
overflow: hidden;
display: none;
position: relative;
}
img {
position: absolute;
}
3、js
//获取页面元素
var box = document.querySelector('.box');
var fdj = document.querySelector('.fdj');
var show = document.querySelector('.show');
var img = document.querySelector('img');
//当鼠标进入的时候
box.onmouseover = function () {
fdj.style.display = 'block';
show.style.display = 'block';
};
//当鼠标在box 上移动的时候
box.onmousemove = function () {
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
//获取鼠标横坐标
var x = event.clientX - 50;
//获取鼠标纵坐标
var y = event.clientY - 50 + scrollTop;
if (x < 0) {
x = 0;
}
if (x > 300) {
x = 300;
}
if (y < 0) {
y = 0;
}
if (y > 300) {
y = 300;
}
fdj.innerHTML = '(x:' + x + ',y:' + y + ')';
fdj.style.left = x + 'px';
fdj.style.top = y + 'px';
var rate = 1600 / 300;
img.style.left = -x * rate + 'px';
img.style.top = -y * rate + 'px';
};
//当鼠标离开 box 的时候
box.onmouseout = function () {
fdj.style.display = 'none';
show.style.display = 'none';
}