用原生js来写放大镜

个人风格是 es5 为主,目前在学习 es6 所以看上去代码有点怪怪的,但反正只有一个我看而已。=v=

//获取对应的变量
let box = document.querySelector('.box');
let smallBox = document.querySelector('.small-box'); //小盒子
let bigBox = document.querySelector('.big-box'); //大盒子
let mask = document.querySelector('.mask'); //蒙板
let bigBoxImg = document.querySelector('.big-box>img'); //大盒子的图片

smallBox.onmouseenter = function () {
    bigBox.style.display = 'block';
        mask.style.display = 'block';

        //蒙版在小盒子里面移动
        document.onmousemove = function (e) {
        //兼容处理
            let event = e || window.event;
        //计算坐标
        let x = event.clientX - box.offsetLeft - mask.offsetWidth/2;
            let y = event.clientY - box.offsetTop - mask.offsetHeight/2;
        //边界判断
            if(x<0){
                x= 1;
            }else if(x >= smallBox.offsetWidth - mask.offsetWidth-1){
                x = smallBox.offsetWidth - mask.offsetWidth-1
            }
            if(y<0){
                y = 1;
            }else if (y>= smallBox.offsetHeight - mask.offsetHeight-1){
                y = smallBox.offsetHeight - mask.offsetHeight-1
            }
        //边界判断<0 后x和y等于1 是为了抵消掉边框的1px。

         //蒙版移动
            mask.style.left = x +'px';
            mask.style.top = y +'px';

        //关联大盒子
        //公式: 大盒子图片的移动距离 = 蒙板移动的距离/小盒子的宽度(高度) * 大盒子的宽度(高度)
            bigBoxImg.style.left = -x /smallBox.offsetWidth * bigBox.offsetWidth +'px';
            bigBoxImg.style.top = -y /smallBox.offsetHeight* bigBox.offsetHeight +'px';

        }
    };

    console.log(bigBoxImg.style.left);

    smallBox.onmouseleave = function () {
        console.log(456);
        bigBox.style.display = 'none';
        mask.style.display = 'none';
        document.onmousemove = null;
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 0. 写在前面 当你开始工作时,你不是在给你自己写代码,而是为后来人写代码。 —— Nichloas C. Zak...
    康斌阅读 5,521评论 1 42
  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 4,542评论 0 13
  • 官方中文版原文链接 感谢社区中各位的大力支持,译者再次奉上一点点福利:阿里云产品券,享受所有官网优惠,并抽取幸运大...
    HetfieldJoe阅读 2,995评论 0 16
  • 1.出差回来 2.继续学习 3.整理尽调项目
    亲爱的小玩子阅读 143评论 0 0
  • 近来总熬夜睡觉了。 烟台的天气忽冷忽热,身上的外衣忽暖忽薄,而心情却平平淡淡着。前几天有人问我:你是不...
    朝暮w阅读 364评论 0 2

友情链接更多精彩内容