效果
思路
有两张图片,小图片用于预览,大图片在鼠标进入小图片时候出现
源码
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>放大镜</title>
<script src="js/index.js"></script>
<link href="css/index.css" type="text/css" rel="stylesheet">
</head>
<body>
<div id="smallImg">
<div id="active"></div>
</div>
<div id="bigImg"></div>
</body>
</html>
css
*{
padding: 0;
margin: 0;
}
div{
display: inline-block;
vertical-align: top;
}
#active{
position: absolute;
top: 0;
left: 0;
display: none;
width: 145px;
height: 190px;
background-color: #FEDE4F;
opacity: 0.6;
cursor: move;
}
#smallImg{
position: relative;
top: 0;
left: 0;
margin: 30px 0 0 30px;
width: 350px;
height: 449px;
background-image: url("../images/small.jpg");
}
#bigImg{
display:none;
margin-top: 30px;
width: 500px;
height: 650px;
background: url("../images/big.jpg") no-repeat;
}
JavaScript
/**
* Created by cgt on 2017/4/9.
*/
window.onload=function(){
var smallImg = document.getElementById("smallImg");
var bigImg = document.getElementById("bigImg");
var active = document.getElementById("active");
smallImg.onmousemove=function(event){
var e = event||window.event;
active.style.display="block";
bigImg.style.display="inline-block";
var times = bigImg.offsetWidth/active.offsetWidth;
var y=e.pageY-smallImg.offsetTop-active.offsetHeight/2;
var x=e.pageX-smallImg.offsetLeft-active.offsetWidth/2;
if(x<0){
x=0;
}else if(x>smallImg.offsetWidth-active.offsetWidth){
x = smallImg.offsetWidth-active.offsetWidth;
}
if(y<0){
y=0;
}else if(y>smallImg.offsetHeight-active.offsetHeight){
y = smallImg.offsetHeight-active.offsetHeight;
}
active.style.top=y+"px";
active.style.left=x+"px";
bigImg.style.backgroundPosition=(-x*times)+"px "+(-y*times)+"px";
}
smallImg.onmouseout=function(){
active.style.display="none";
bigImg.style.display="none";
}
}