放大鏡: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)複製代碼
相關文章
相關標籤/搜索