您的位置:首页 > Web前端 > JavaScript

原生JS实现简单放大镜效果

2018-12-06 23:12 405 查看

【前言】

    本文介绍下原生JS实现简单图片放大镜效果

 

【主体】

   时间问题,直接上源码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>放大镜</title>
<style type="text/css">
/*代码初始化*/
*{
margin: 0;
padding: 0;
}
/*代码主体*/
.small_box{
width: 300px;
height: 300px;
border: 1px solid black;
float: left;
cursor: move;
margin-left:100px;
margin-top:100px;
position: relative;
}
.small_box img{
width: 300px;
height: 300px;
}
.fdj{
width: 50%;
height: 50%;
background-color:rgba(200,200,1,0.6)
4000
;
position:absolute;
left:0px;
top:0px;
display:none;
}
.big_box{
width:300px;
height:300px;
/*border:1px solid black;*/
overflow:hidden;
box-sizing: border-box;
float:left;
margin-top:100px;
position:relative;
display:none;
}
.big_box img{
position: absolute;
width: 200%;
height: 200%;
}
.small_box .active,.active{
display: block;
}
</style>
</head>
<body>
<div class="small_box">
<img src="01.jpg" alt="汪星人">
<div class="fdj"></div>
</div>
<div class="big_box">
<img class="big_img" src="01.jpg" alt="汪星人">
</div>
<script type="text/javascript">
var small_box = document.getElementsByClassName("small_box")[0];//小盒子
var fdj = document.getElementsByClassName("fdj")[0];//小盒子中的黄色区域
var big_box = document.getElementsByClassName("big_box")[0];//大盒子
var big_img = document.getElementsByClassName("big_img")[0];//放大的图片
//鼠标进入小盒子区域内,显示黄色区域和大盒子
small_box.onmouseenter = function(){
fdj.className = "fdj active";
big_box.className = "big_box active";
}
//鼠标离开小盒子区域,不显示黄色区域和大盒子
small_box.onmouseleave = function(){
fdj.className = "fdj";
big_box.className = "big_box";
}
//鼠标在小盒子内移动
small_box.onmousemove = function(event){
// console.log(event.clientX);//clientX 设置或获取鼠标指针位置相对于窗口客户区域的 x 坐标
// console.log(this.offsetLeft);//当前元素顶部相对于指定定位属性祖先元素左侧的偏移量
// console.log(fdj.offsetWidth/2);//小黄盒子宽度一半
var x = event.clientX-this.offsetLeft-fdj.offsetWidth/2;//事件对象在小盒子内的横向偏移量
var y = event.clientY-this.offsetTop-fdj.offsetHeight/2;//竖向偏移量

if(x<0){x=0};//当左偏移出小盒子时,设为0
if(y<0){y=0};//当上偏移出小盒子时,设为0

if(x>this.offsetWidth-fdj.offsetWidth){
x = this.offsetWidth-fdj.offsetWidth;//当右偏移出小盒子时,设为小盒子的宽度-黄色放大区域宽度
}
if(y>this.offsetHeight-fdj.offsetHeight){
y = this.offsetHeight-fdj.offsetHeight;//当下偏移出小盒子时,设为小盒子的高度-黄色放大区域高度
}

fdj.style.left = x + "px";//黄色放大区域距离小盒子左偏距
fdj.style.top = y + "px";//黄色放大区域距离小盒子上偏距

big_img.style.left = -x*2 + "px";//放大图片移动方向相反,偏移距离加倍
big_img.style.top = -y*2 + "px";
}
</script>
</body>
</html>

 

 

.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: