第22天的實作是作者wesbos看到stripe這個網頁,覺得導覽列非常特別,而衍伸出來的議題。
這個實作目標是要當滑鼠移到特定的元素時,會在該元素的後面新增背景,做到類似hightligh的效果。
首先,先取得網頁上全部當滑鼠移到特定元素時,這次的實作是取得a作為動態效果的目標。
在每一個a元件建立mouseenter事件,指說當滑鼠移到a元件就觸發事件。
trigger.forEach(a => a.addEventListener('mouseenter', hoverHighlight))
而hightligh的效果就是該指到的元素後面加入span元素,而span元素的背景設為全白。因此在每次事件觸發時新增span元素
const highlight = document.createElement('span')
highlight.classList.add('highlight')
document.body.appendChild(highlight)
當事件內容為取得被滑鼠指到的元素的位置,利用getBoundingClientRect()來取得a元素在網頁的相對位置的值和寬高度,之後把取得a元素的寬、高度設定為span的寬、高度,而span的左邊界距離為a元素的左邊界距離加上視窗在網頁中左移的距離,上邊界的距離要為a元素的上邊界距離加上視窗在網頁中下移的距離。
原因為網頁的寬、高度會大於可視畫面的寬、高度,網頁可以被滾動,為了取得a元素在網頁中的絕對位置,要在getBoundingClientRect()取得的相對位置中加入網頁滾動左邊和上邊的距離。
function hoverHighlight() {
const linkcoords = this.getBoundingClientRect();
console.log('位置:',linkcoords);
coord={
width: linkcoords.width,
height: linkcoords.height,
left: linkcoords.left + window.scrollX,
top: linkcoords.top + window.scrollY,
}
highlight.style.width = coord.width +'px'
highlight.style.height = coord.height+'px'
highlight.style.transform =`translate(${coord.left}px, ${coord.top}px)`
}
之後在a元素後面加入span元素並加入class效果。
這樣就可以做到當指定特定元素a時,可在該元素類似加入hightligh的效果。
<nav>
<ul class="menu">
<li><a href="">Home</a></li>
<li><a href="">Order Status</a></li>
<li><a href="">Tweets</a></li>
<li><a href="">Read Our History</a></li>
<li><a href="">Contact Us</a></li>
</ul>
</nav>
<div class="wrapper">
<p>Lorem ipsum dolor sit amet, <a href="">consectetur</a> adipisicing elit. Est <a href="">explicabo</a> unde natus necessitatibus esse obcaecati distinctio, aut itaque, qui vitae!</p>
<p>Aspernatur sapiente quae sint <a href="">soluta</a> modi, atque praesentium laborum pariatur earum <a href="">quaerat</a> cupiditate consequuntur facilis ullam dignissimos, aperiam quam veniam.</p>
<p>Cum ipsam quod, incidunt sit ex <a href="">tempore</a> placeat maxime <a href="">corrupti</a> possimus <a href="">veritatis</a> ipsum fugit recusandae est doloremque? Hic, <a href="">quibusdam</a>, nulla.</p>
<p>Esse quibusdam, ad, ducimus cupiditate <a href="">nulla</a>, quae magni odit <a href="">totam</a> ut consequatur eveniet sunt quam provident sapiente dicta neque quod.</p>
<p>Aliquam <a href="">dicta</a> sequi culpa fugiat <a href="">consequuntur</a> pariatur optio ad minima, maxime <a href="">odio</a>, distinctio magni impedit tempore enim repellendus <a href="">repudiandae</a> quas!</p>
</div>
Element.getBoundingClientRect()
Element.getBoundingClientRect()這個方法是取得元件在瀏覽器可視畫面上的大小和位置。
The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.
共取得8個屬性
width為元素的寬度。height為元素的高度。left為元素離網頁可視畫面左邊界的距離right為元素寬度width加left的距離top為元素離網頁可視畫面上邊界的距離bottom為元素高度height加height的距離x為網頁可視畫面的位置X軸,以元素的左上角測量。y為網頁可視畫面的位置Y軸,以元素的左上角測量。width,height為固定值。.getBoundingClientRect()