放大镜:onmousemove版 京东、淘宝版

###以前关于放大镜的文章【onmousedown\onmousemove\onmouseenter版】,我仔细看了一个各大电商网站,其实都不是这个样子。并且这个版本的比较麻烦。那么今天就给你们带来单纯的onmousemove版的,更简单,更值得你看~当你再次写电商网站的时候绝对不慌!css

放大镜:onmousemove版 京东、淘宝版(原生js)函数

对,我就是这么的爱玩原生js~.网站

虽是效果不一样,可是实现放大镜的思路是同样的。为了你们方便理解,我把HTML的结构也给你们写出来,可是css仍是须要你们本身去琢磨,去添加。个人目的是让你们更好的理解编码过程与案例思路,而不是想让你们成为代码的搬运工。编码

<body>
    <div class="left">
        <img src="./imgs/small.jpg">
        <div class="square"></div>
        <div class="opacity"></div>
        <!-- 这是一个具备防抖功能的遮罩层 -->
    </div>

    <div class="right"></div>
    <script>
        //原生DOM节点的操做,万变不离其中,先取到它
        var left = document.querySelector('.left');
        var square = document.querySelector('.square');
        left.onmousemove = function (evt) {
            //事件发生时,咱们须要知道事件的相关信息,事件信息一般放在了事件对象中,事件处理函数的参数,就是事件对象,即上文的evt.
            var x = evt.offsetX;
            var y = evt.offsetY;
            //console.log(square.style.width)
            //注意:上文在输出square是取不到square的width,由于咱们以前设置的行内样式,而不是内联样式。

            //咱们须要取到光标的位置
            //咱们要将光标的位置,与square的位置相关联起来,而且设置光标的位置在square元素的正中心。
            x -= parseInt(getComputedStyle(square).width) / 2;
            y -= parseInt(getComputedStyle(square).height) / 2;
            //限制square元素的移动范围,只在left中移动。
            if (x < 0) {
                x = 0
            }
            if (y < 0) {
                y = 0
            }
            if (x > parseInt(getComputedStyle(left).width) - parseInt(getComputedStyle(square).width)) {
                x = parseInt(getComputedStyle(left).width) - parseInt(getComputedStyle(square).width)
            }
            if (y > parseInt(getComputedStyle(left).height) - parseInt(getComputedStyle(square).height)) {
                y = parseInt(getComputedStyle(left).height) - parseInt(getComputedStyle(square).height)
            }
            square.style.left = x + 'px';
            square.style.top = y + 'px';

            //下面咱们经过square的坐标来设置右边大图的坐标关系
            var right = document.querySelector('.right');
            right.style.backgroundPosition = `${x * -3}px ${y * -3}px`
            //从中咱们能够看出在ES6中新加的模版字符串是很是强大的应用,它是能够嵌套变量的。有了它真的给咱们省了很多的麻烦。
            left.onmouseleave = function() {
                right.style.display = "none";
            }
        }
    </script>
</body>
![](https://user-gold-cdn.xitu.io/2019/10/17/16dd79281142ae22?w=270&h=179&f=jpeg&s=25808)
![](https://user-gold-cdn.xitu.io/2019/10/17/16dd792a5f901a41?w=1080&h=718&f=jpeg&s=307702)复制代码
相关文章
相关标签/搜索