Javascript_30_22


こんにちは!


デレクです😁


時間...流れが速いなぁ…!このjavascript 30シリーズは近いうちに終わります
早く終わるように頑張ります:)
今日はDay 22の計画を整理します
かわいいけどいつか使える機能

22. Follow along Link Highlighter


n/a.ターゲット



段落内のaラベルにマウスを置くと、そのラベルが強調されます.
マウスが文書中のaタグの上を移動すると、このタグを強調表示することができる.

DerekとWes Bosの実装コード

const triggers = document.querySelectorAll("a");

const highlight = document.createElement("span");
highlight.classList.add("highlight");
document.body.append(highlight);

function highlightLink() {
  const linkCoords = this.getBoundingClientRect();
  const coords = {
    width: linkCoords.width,
    height: linkCoords.height,
    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(link => link.addEventListener("mouseenter", highlightLink));
まず、triggers変数は、段落内のすべてのaタグ配列を有する.
また、highlight変数を作成し、まずdocument.bodyappendを行います.
次に、aタグを追跡するために、この2つの方法を使用します.

1.hightlightLink関数


この関数はmouseenter eventに登録されています.
triggers.forEach(link => link.addEventListener("mouseenter", highlightLink));
aタグアレイtriggersmouseenterイベントhighlightLink関数を登録した.
function highlightLink() {
  const linkCoords = this.getBoundingClientRect();
  const coords = {
    width: linkCoords.width,
    height: linkCoords.height,
    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)`;
}
初めて見たgetBoundingClientRect()関数!MDNによれば、
The Element.getBoundingClientRect() method returns a DOMRect object providing information about the size of an element and its position relative to the viewport.
すなわち,あるオブジェクトに対して,寸法と位置を教える関数と見なすことができる.
これは、オブジェクトの値がtop, bottom, left, right, width, height, x, yであることを示します.
ここで確認できます.triggersのイベント、thisgetBoundingClientRect()は、各aタグの位置および属性を返します.その価格はlinkCoordsです.

これで、値段を確認できます!
これに基づいて、前述のspanマークhighlightを調整する.
const coords = {
  width: linkCoords.width,
  height: linkCoords.height,
  top: linkCoords.top + window.scrollY,
  left: linkCoords.left + window.scrollX
};
各属性値がcoodsのオブジェクトを作成して保存します.
highlight.style.width = `${coords.width}px`;
highlight.style.height = `${coords.height}px`;
highlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`;
これにより、highlightstyleのプロパティを変更して移動できます.
これは比較的簡単なテーマです!

初めて使用したgetBoundingClientRect()関数を用いて簡単にした.
エラーや修正が必要な場合は、いつでもフィードバックしてください.
ありがとう!🤗