仿京东放大镜---JS实现

实现效果

仿京东放大镜---JS实现_第1张图片

H5代码


<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>京东放大镜title>
head>

<body>
    <div class="box">
        <img src="https://img12.360buyimg.com/n1/s450x450_jfs/t1/59022/28/10293/141808/5d78088fEf6e7862d/68836f52ffaaad96.jpg" alt="">
        <div class="mask">div>
        <div class="big">
            <img src="https://img12.360buyimg.com/n1/s450x450_jfs/t1/59022/28/10293/141808/5d78088fEf6e7862d/68836f52ffaaad96.jpg" alt="" class="bigImg">
        div>
    div>
body>

html>

CSS

	

JS代码

	<script>
        window.addEventListener('load', function() {
            var box = document.querySelector('.box');
            var mask = document.querySelector('.mask');
            var big = document.querySelector('.big');
            // 鼠标进入事件
            box.addEventListener('mouseover', function(e) {
                mask.style.display = 'block';
                big.style.display = 'block';
            });
            // 鼠标移出事件
            box.addEventListener('mouseout', function() {
                mask.style.display = 'none';
                big.style.display = 'none';
            });
            // 鼠标移动事件
            box.addEventListener('mousemove', function(e) {
                // 确认mask 的位置
                var x = e.pageX - this.offsetLeft - mask.offsetWidth / 2;
                var y = e.pageY - this.offsetTop - mask.offsetHeight / 2;
                // 最大偏移值,即大盒子-放大镜层
                var maskMax = box.offsetWidth - mask.offsetWidth;

                // 超出偏移量,强制修改
                if (x <= 0) x = 0;
                if (x >= maskMax) x = maskMax;
                if (y <= 0) y = 0;
                if (y >= maskMax) y = maskMax;

                // 修改放大镜层的位置
                mask.style.left = x + 'px';
                mask.style.top = y + 'px';

                // 计算大图的最大距离
                var bigImg = document.querySelector('.bigImg');
                var bigMax = bigImg.offsetWidth - big.offsetWidth;
                // 两最大距离的商,即放大的倍数
                var boom = bigMax / maskMax;
                var bigX = x * boom;
                var bigY = y * boom;
                // 修改大图在盒子中的定位
                bigImg.style.left = -bigX + 'px';
                bigImg.style.top = -bigY + 'px';
            });
        });
    </script>

你可能感兴趣的:(JavaScript,html,css,js,javascript,京东放大器)