JavaScipt30(第二十二个案例)(主要知识点:getBoundingClientRect)

这是第二十二个案例,这个例子实现的是鼠标移入a标签时,将其高亮。

附上项目链接: https://github.com/wesbos/JavaScript30

以下为注释后的源码:

<script>
    const triggers = document.querySelectorAll('a');
    const highlight = document.createElement('span');
    highlight.classList.add('highlight');
    document.body.appendChild(highlight);

    function highlightLink() {
        // 返回值是一个DOMRect对象,DOMRect 对象包含了一组用于描述边框的只读属性——left、top、right和bottom,单位为像素。
        const linkCoords = this.getBoundingClientRect();
        const coords = {
            width: linkCoords.width,
            height: linkCoords.height,
            // 这里有个值得注意的点是,因为DOMRect是相对于视口的左上角位置而言的,所以需要加上滚动的scrollY或scrollX
            top: linkCoords.top + window.scrollY,
            left: linkCoords.left + window.scrollX
        };

        highlight.style.width = `${coords.width}px`;
        highlight.style.height = `${coords.height}px`;
        // 除了定位外的另一种移到某个位置的方法,要记得用
        highlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`;
    }

    triggers.forEach(a => a.addEventListener('mouseenter', highlightLink));
</script>

猜你喜欢

转载自www.cnblogs.com/wangxi01/p/10675524.html