2

商城项目中,有鼠标移入图片放大的功能,研究一下实现

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Image zoom</title>
    </head>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }

        #image {
            width: 300px;
            height: 300px;
            background-color: #000;
            background-image: url(https://placekitten.com/900/900);
            background-size: 300px 300px;
            background-repeat: no-repeat;
        }

        #image[zoomed] {
            background-size: 900px 900px;
            background-position: calc(var(--x) * 100%) calc(var(--y) * 100%);
        }
    </style>
    <body>
        <div id="image"></div>
    </body>
    <script>
        let el = document.querySelector('#image')

        // PC端操作
        el.addEventListener('mouseenter', enterHandler)
        el.addEventListener('mousemove', moveHandler)
        el.addEventListener('mouseleave', leaveHandler)

        // 移动端操作
        el.addEventListener('touchstart', enterHandler)
        el.addEventListener('touchmove', moveHandler)
        el.addEventListener('touchend', leaveHandler)

        function enterHandler(e) {
            e.target.setAttribute('zoomed', 1)
            moveHandler(e)
        }

        function moveHandler(e) {
            // getBoundingClientRect用于获取元素相对于视窗的位置集合。集合中有top, right, bottom, left等属性
            let rect = e.target.getBoundingClientRect()
            let offsetX, offsetY
            let isH5 = ['touchstart', 'touchmove', 'touchend'].includes(e.type)
            // 是移动端,并且touches事件存在
            if (isH5 && e.touches[0]) {
                offsetX = e.touches[0].pageX - rect.left
                offsetY = e.touches[0].pageY - rect.top

                e.preventDefault()
            } else {
                // PC端
                offsetX = e.offsetX
                offsetY = e.offsetY
            }
            // 元素的位置信息
            let x = offsetX / rect.width
            let y = offsetY / rect.height
            // 设置元素属性,用于计算background-position的位置
            e.target.style.setProperty('--x', x)
            e.target.style.setProperty('--y', y)
        }

        function leaveHandler(e) {
            e.target.removeAttribute('zoomed')
            moveHandler(e)
        }
    </script>
</html>

具体效果复制下去打开看看


万年打野易大师
1.5k 声望1.1k 粉丝