1、鼠标放大镜效果
鼠标放大镜效果,将鼠标移入到左图片,则可以在其右边看到放大的图片,且鼠标移动滑块的大小即为右图显示图片。实际效果如下图所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
#little_image {
width: 400px;
height: 400px;
position: absolute;
top: 0px;
left: 0px;
}
#image {
display: block;
width: 400px;
height: 400px;
position: absolute;
}
#big_image {
width: 500px;
height: 500px;
border: 1px solid grey;
overflow: hidden;
display: none;
position: absolute;
top: 0px;
left: 400px;
}
#images {
display: block;
width: 1000px;
height: 1000px;
position: absolute;
}
#slider_block {
width: 200px;
height: 200px;
position: absolute;
border: 1px solid lightgrey;
cursor: all-scroll;
display: none;
}
</style>
</head>
<body>
<div id="little_image">
<img src="img/1.png" id="image"/>
<div id="slider_block">
</div>
</div>
<div id="big_image">
<img src="img/31.png" id="images"/>
</div>
</body>
<script type="text/javascript">
var littleImage = document.getElementById(‘little_image‘);
var bigImage = document.getElementById(‘big_image‘);
var sliderBlock = document.getElementById(‘slider_block‘);
//为littleImage添加鼠标移入事件
littleImage.onmousemove = function(event) {
event = event || window.event;
sliderBlock.style.display = "block"; //移入鼠标显示sliderBlock
bigImage.style.display = "inline-block"; //移入鼠标显示bigImage
// 1、限定sliderBlock的活动范围
var disX = event.clientX - sliderBlock.offsetWidth / 2; //鼠标点击位置-移动块宽度的1/2
var disY = event.clientY - sliderBlock.offsetHeight / 2;
//最大移动位置就是little_image的宽度-移动块的宽度
var distenceMaxX = littleImage.offsetWidth - sliderBlock.offsetWidth;
var distenceMaxY = littleImage.offsetHeight - sliderBlock.offsetHeight;
if (disX < 0) {
disX = 0;
} else if (disX >= distenceMaxX) {
disX = distenceMaxX
}
if (disY < 0) {
disY = 0;
} else if (disY >= distenceMaxY) {
disY = distenceMaxY;
}
// 2、通过改变sliderBlock的left和top的指来让sliderBlock随着鼠标移动
sliderBlock.style.left = disX + "px";
sliderBlock.style.top = disY + "px";
// 3、通过计算sliderblock在littleImage的比例,计算bigImage在大图中显示的比例
var scaleX = disX / distenceMaxX;
var scaleY = disY / distenceMaxY;
var images = document.getElementById(‘images‘);
bigImage.scrollLeft = (images.offsetWidth - bigImage.offsetWidth) * scaleX;
bigImage.scrollTop = (images.offsetHeight - bigImage.offsetHeight) * scaleY;
}
//添加鼠标移出事件
littleImage.onmouseleave = function() {
sliderBlock.style.display = ‘none‘; // sliderBlock隐藏
bigImage.style.display = ‘none‘; // bigImage隐藏
}
</script>
</html>
附:offset | client | scroll 关系图