关于html5:鼠标移入放大图片预览效果实现

56次阅读

共计 1682 个字符,预计需要花费 5 分钟才能阅读完成。

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

<!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>

具体成果复制上来关上看看

正文完
 0