HTML结构
<div class="box" id="box">
<div id="smallBox">
![](images/pic001.jpg)
<span id="mask"></span>
</div>
<div id="bigBox">
![](images/pic01.jpg)
</div>
<div id="list">
![](images/pic0001.jpg)
![](images/pic0002.jpg)
![](images/pic0003.jpg)
</div>
</div>
Css样式
<style>
* {
margin: 0;
padding: 0;
border: 0;
}
img {
vertical-align: top;
}
.box {
width: 350px;
height: 350px;
margin: 50px;
position: relative;
border: 1px solid #cccccc;
}
#smallBox {
width: 100%;
height: 100%;
position: relative;
cursor: move;
}
#mask {
width: 100px;
height: 100px;
background: rgba(255, 255, 0, .4);
position: absolute;
left: 0;
top: 0;
display: none;
}
#bigBox {
width: 500px;
height: 500px;
border: 1px solid #ccc;
position: absolute;
left: 360px;
top: 0;
overflow: hidden;
display: none;
}
#bigBox img {
width: 800px;
position: absolute;
left: 0;
top: 0;
}
#list {
margin-top: 20px;
}
</style>
Js代码
<script>
window.onload = function () {
// 1. 获取标签
var box = document.getElementById('box');
var smallbox = box.children[0];
var mask = smallbox.children[1];
var bigBox = box.children[1];
var bigImg = bigBox.children[0];
var list = box.children[2];
var allLis = list.children;
// 2. 鼠标监听事件
smallbox.onmouseover = function () {
// 2.1 显示隐藏的盒子
mask.style.display = 'block';
bigBox.style.display = 'block';
// 2.2 鼠标移动跟随
smallbox.onmousemove = function (event) {
var event = event || window.event;
var pointX = event.pageX - box.offsetLeft - mask.offsetWidth / 2;
var pointY = event.pageY - box.offsetTop - mask.offsetHeight / 2;
// 2.3 计算边缘值
if (pointX < 0) {
pointX = 0;
}
else if (pointX >= box.offsetWidth - mask.offsetWidth) {
pointX = box.offsetWidth - mask.offsetWidth - 1;
}
if (pointY < 0) {
pointY = 0;
}
else if (pointY >= box.offsetHeight - mask.offsetHeight) {
pointY = box.offsetHeight - mask.offsetHeight - 1;
}
// 2.4 赋值给小黄盒子
mask.style.left = pointX + 'px';
mask.style.top = pointY + 'px';
// 2.5 开始移动大图片
// smallX / bigX = smallBox.width / 大图片的宽度
// bigX = smallX / (smallBox.width / 大图片的宽度)
bigImg.style.left = - pointX / (smallbox.offsetWidth / bigBox.offsetWidth) + 'px';
bigImg.style.top = - pointY / (smallbox.offsetHeight / bigBox.offsetHeight) + 'px';
}
// 隐藏显示的盒子
smallbox.onmouseout = function () {
mask.style.display = 'none';
bigBox.style.display = 'none';
}
}
// 3. 图片对应效果
for (var i = 0; i < allLis.length; i ++) {
(function (index) {
var img = allLis[i];
img.onmouseover = function () {
bigImg.src = 'images/pic0' + index + '.jpg'
smallbox.children[0].src = 'images/pic00' + index + '.jpg';
}
}(i + 1));
}
}
</script>
特效展示