WES BOS系列影片
Alex快速導讀系列影片
今天的練習是用js控制滑鼠游標,
當滑鼠游標到達當前的連結時,
我們使用一個新的方法
getBoundingClientRect()
得到當前連結區塊的長寬,並使highlight樣式
跟隨連結的長寬做動態變化
1.先抓取頁面上所有的a連結。
因為是練習,所以抓取的方式就很簡單,
直接抓全部標籤a的元素,但在正式專案還是需要注意抓取的方式
還是只抓取需要更動的部分就好,不要造成同事的困擾喔
const triggers = document.querySelectorAll('a')
2.用js創造一個span元素,待會控制它的長寬與位置即可
const highlight = document.createElement('span')
highlight.classList.add('highlight')
document.body.appendChild(highlight)
3.對所有a元素做,mouseenter的監聽
triggers.forEach(a => {
  a.addEventListener('mouseenter', highlightLink)
})
4.製作 highlightLink 函式
function highlightLink () {
  const linkCoords = this.getBoundingClientRect()
  console.log(linkCoords);
}
現在可以得到各a元素的座標與長寬
先設定長寬
function highlightLink () {
  const linkCoords = this.getBoundingClientRect();
  console.log(linkCoords);
  const coords = {
  width: linkCoords.width,
  height: linkCoords.height,
  };   
  highlight.style.width = `${coords.width}px`
  highlight.style.height = `${coords.height}px`
}
可以看到樣式的長寬正在變化,但位置依舊都留在左上角,
所以現在來調整位置
function highlightLink () {
  const linkCoords = this.getBoundingClientRect();
  console.log(linkCoords);
  const coords = {
    width: linkCoords.width,
    height: linkCoords.height,
    top:linkCoords.top,
    left:linkCoords.left,
  };   
  highlight.style.width = `${coords.width}px`
  highlight.style.height = `${coords.height}px`
  highlight.style.top = `${coords.top}px`
  highlight.style.left = `${coords.left}px`
}
但如果視窗捲軸往下呢?位置就跑掉了
5.加上捲軸的移動
function highlightLink () {
...
  const coords = {
    width: linkCoords.width,
    height: linkCoords.height,
    top:linkCoords.top + window.scrollY,
    left:linkCoords.left + window.scrollX,
  };   
...
}
今天的練習完成囉,完整的程式碼請直接點擊下方codePen連結
codePen
或者也可以直接到WES BOS的網站下載打包好的檔案
javascript30