原生js的放大鏡怎麼做,怎麼實現放大鏡效果_n倍放大鏡
示意圖和思路:
效果圖:
程式碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
*{
margin:0;
padding:0;
list-style: none
}
/*小圖作為box的背景*/
#box{
position:relative;
width:300px;
height:400px;
background-image:url(img/timg1.jpg);
background-size:300px 400px;
}
/*放大鏡*/
#bigMirror{
position:absolute;
left:50px;
top:100px;
width:60px;
height:80px;
background-color:red;
opacity:0.4;
}
/*大圖的可視區域*/
#show{
position:absolute;
left:310px;
top:0px;
width:120px;/*是放大鏡尺寸的n倍*/
height:160px;/*是放大鏡尺寸的n倍*/
border:1px solid black;
overflow:hidden;
}
img{
position:absolute;
left:-50px;
top:-100px;
width:600px;/*是小圖的n倍*/
height:800px;/*是小圖的n倍*/
}
</style>
</head>
<body style="height:1000px; width:1000px;">
<div id="box">
<div id="bigMirror">
</div>
<div id="show">
<img id="bigImg" src="img/timg1.jpg" />
</div>
</div>
</body>
</html>
<script type="text/javascript" src="tools/util.js"></script>
<script type="text/javascript">
window.onload = function(){
//放大鏡的尺寸;
let bigMirrorWidth = 60;
let bigMirrorHeight = 80;
$("box").onmousemove = function(event){
let evt = event || window.event;
//一、放大鏡跟著滑鼠走
//1、計算滑鼠距離box左上角的位置
let left = evt.pageX-this.offsetLeft;//滑鼠距離頁面的橫向距離-box距離頁面的橫向距離
let top = evt.pageY-this.offsetTop;
//2、計算放大鏡的位置
let bigMirrorLeft = left-bigMirrorWidth/2;
let bigMirrorTop = top-bigMirrorHeight/2;
//3、邊界處理
//if(bigMirrorLeft>=小圖的寬度-放大鏡的寬度){
if(bigMirrorLeft>=$("box").offsetWidth-$("bigMirror").offsetWidth){
bigMirrorLeft =$("box").offsetWidth-$("bigMirror").offsetWidth;
}else if(bigMirrorLeft<=0){
bigMirrorLeft =0;
}
if(bigMirrorTop>=$("box").offsetHeight-$("bigMirror").offsetHeight){
bigMirrorTop =$("box").offsetHeight-$("bigMirror").offsetHeight;
}else if(bigMirrorTop<=0){
bigMirrorTop =0;
}
//4、放大鏡的移動
$("bigMirror").style.left = bigMirrorLeft+"px";
$("bigMirror").style.top = bigMirrorTop+"px";
//二、大圖的移動
$("bigImg").style.left = -2*bigMirrorLeft+"px";//2是表示倍數是2倍
$("bigImg").style.top = -2*bigMirrorTop+"px";
}
}
</script>