勇气不怕 2022-04-10 12:50 采纳率: 75%
浏览 40
已结题

js实现放大镜效果,出错

我想要写一个放大镜效果的图片效果

相关html代码

<div class="big-ring">
                    <img src="../images/big-ring.jpg" alt="" width="100%"class="first-img">
                    <!-- 放大镜圆圈 -->
                    <div class="move">
                        <img src="../images/big-ring.jpg" alt="">
                    </div>
            </div>
<script>
//     // 获取元素对象
    const container=document.querySelector('.big-ring');
    const move=document.querySelector('.move');
    const bigimg=document.querySelector('.move img');
    container.addEventListener('mouseover',function(){
        move.classList.remove('hidden');
    });
    container.addEventListener('mouseout',function(){
        move.classList.add('hidden');
    })

    // 放大镜跟随鼠标移动,绑定container的鼠标移动事件
container.addEventListener('mousemove',function(e){
//获取鼠标距离左侧的便宜
let x=e.clientX;
//获取container距离左侧的偏移
let l=container.offsetLeft;
let moveLeft=x-l-move.offsetWidth/2;
if(moveLeft <=0) moveLeft=0;
let maxLeft=container.offsetWidth-move.offsetWidth;
if(moveLeft>=maxLeft) moveLeft=maxLeft;
// 设置样式
move.style.left=moveLeft+"px";
let bigimgleft = (moveLeft +move.offsetWidth/2) / container.offsetWidth * bigimg.offsetWidth - move.offsetWidth/2;
bigimg.style.left=-bigimgleft+"px";


let y=e.clientY;
// //获取container距离左侧的偏移
let t=container.offsetTop;
let moveTop=y-t-move.offsetHeight/2;
if(moveTop <=0) moveTop=0;
let maxTop=container.offsetHeight-move.offsetHeight;
if(moveTop>=maxTop) moveTop=maxTop;
// // 设置样式
move.style.top=moveTop+"px";
let bigimgTop=(moveTop +move.offsetHeight/2)/container.offsetHeight*bigimg.offsetHeight-move.offsetHeight/2;
bigimg.style.top=-bigimgtop+"px";
});
</script>

css代码

放大镜
*{
    margin:0;
    padding:0;
}
.body{
    display: flex;
    justify-content: center;
    align-items: center;
    height:100vh;
}

.big-ring{
    width: 500px;
    height:500px;
    position: relative;
    border:solid 1px #ddd;
}
.move{
    width: 300px;
    height:300px;
    border:solid 10px #000;
    position: absolute;
    left:0;
    top:0;
    overflow: hidden;
    box-shadow: 0 0 20px #000;
}
.move img{
    position:absolute;
    left:0;
    top:0;
width:800px;
height:800px;
}
.hidden{
    opacity: 0;

}

运行结果
放大镜向下移动的时候,放大镜内的内容不对应鼠标所指的内容

  • 写回答

1条回答 默认 最新

  • 你好!机器人 2022-04-10 13:28
    关注

    这里写错了

    let bigimgTop = (moveTop + move.offsetHeight / 2) / container.offsetHeight * bigimg.offsetHeight - move.offsetHeight / 2;
    bigimg.style.top = -bigimgTop + "px";
    .
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 4月26日
  • 已采纳回答 4月18日
  • 创建了问题 4月10日

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)