样式定义
* {padding: 0; margin: 0;} /* 重置页面默认样式 */
.div1 {position: relative; margin: 0 auto; width: 432px; height: 224px; border: 1px solid #000;}
.div2 {position: absolute; display: none; width: 50px; height: 50px; background: yellow;}
.div3 {width: 200px; height: 200px; overflow: hidden;}
.img {position: relative;}
HTML结构
<div class="div1">
<img src="img/1101.jpg">
<div class="div2"></div>
</div>
<div class="div3">
<img src="img/11.jpeg" class="img">
</div>
JavaScript脚本
var div1 = getClass(document, 'div1')[0]; // 获取div1元素
var div2 = getClass(document, 'div2')[0]; // 获取div2元素
var div3 = getClass(document, 'div3')[0]; // 获取div3元素
var img = getClass(document, 'img')[0]; // 获取img元素
// 鼠标移入div1时触发
div1.onmouseover = function () {
div2.style.display = 'block'; // 显示div2元素
div1.onmousemove = function (ev) {
var ev = ev || window.event;
var L = ev.clientX - div1.offsetLeft - div2.offsetWidth / 2; // 计算div2的水平位置
var T = ev.clientY - div1.offsetTop - div2.offsetHeight / 2; // 计算div2的垂直位置
// 边界检测,确保div2不超出div1的边界
if (L < 0) {
L = 0;
} else if (L > div1.offsetWidth - div2.offsetWidth) {
L = div1.offsetWidth - div2.offsetWidth;
}
if (T < 0) {
T = 0;
} else if (T > div1.offsetHeight - div2.offsetHeight) {
T = div1.offsetHeight - div2.offsetHeight;
}
div2.style.left = L + 'px'; // 设置div2的水平位置
div2.style.top = T + 'px'; // 设置div2的垂直位置
// 计算图片位置,实现放大效果
var X = L / (div1.offsetWidth - div2.offsetWidth);
var Y = T / (div1.offsetHeight - div2.offsetHeight);
img.style.left = -X * (div1.offsetWidth - div2.offsetWidth) + 'px';
img.style.top = -Y * (div1.offsetHeight - div2.offsetHeight) + 'px';
};
};
// 鼠标移出div1时触发
div1.onmouseout = function () {
div2.style.display = 'none'; // 隐藏div2元素
};