<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
img{
display: block;
border: none;
}
#zoomBox{
position: relative;
width: 400px;
border: 1px solid #CECECE;
}
#midArea{
width: 400px;
height: 400px;
}
#midArea img{
width: 400px;
height: 400px;
}
#zoom{
display: none;
position: absolute;
width: 200px;
height: 200px;
background: yellow;
opacity: 0.5;
cursor: move;
}
#bigArea{
display: none;
position: absolute;
top: -1px;
left: 401px;
width: 400px;
height: 400px;
overflow: hidden;
border: 1px solid #CECECE;
}
#bigArea img{
position: absolute;
width: 800px;
height: 800px;
}
</style>
</head>
<body>
<div id="zoomBox">
<div id="midArea">
<img src="img/01.jpg">
<div id="zoom"></div>
</div>
<div id="bigArea">
<img src="img/01.jpg">
</div>
</div>
<script type="text/javascript">
function $id(id){
return document.getElementById(id);
}
var oZoomBox = $id("zoomBox");
var oMidArea = $id("midArea");
var oMidImg = oMidArea.children[0];
var oZoom = $id("zoom");
var oBigArea = $id("bigArea");
var oBigImg = oBigArea.children[0];
oMidArea.onmouseover = function(){
oZoom.style.display = "block";
oBigArea.style.display = "block";
}
oMidArea.onmouseout = function(){
oZoom.style.display = "none";
oBigArea.style.display = "none";
}
var cw = oMidArea.clientWidth;
var ch = oMidArea.clientHeight;
oMidArea.onmousemove = function(e){
var evt = e || event;
var zw = oZoom.offsetWidth;
var zh = oZoom.offsetHeight;
//var _left = evt.offsetX - oZoom.offsetWidth/2;
//var _top = evt.offsetY - oZoom.offsetHeight/2;
var _left = evt.clientX - oZoomBox.offsetLeft - oZoom.offsetWidth/2;
var _top = evt.clientY -oZoomBox.offsetTop - oZoom.offsetHeight/2;
_left = _left <= 0 ? 0 : _left>=cw-zw ? cw-zw : _left;
_top = _top <= 0 ? 0 : _top>= ch-zh ? ch-zh : _top;
oZoom.style.left = _left + "px";
oZoom.style.top = _top + "px";
oBigImg.style.left = - _left/cw*oBigImg.offsetWidth + "px";
oBigImg.style.top = - _top/ch*oBigImg.offsetHeight + "px";
}
</script>
</body>
</html>
JS代码实现放大镜的效果
最新推荐文章于 2023-06-15 17:34:06 发布