LoginSignup
1
1

More than 5 years have passed since last update.

[javascript]画面上でクリックした位置にある重なっている要素を取得する

Posted at

メモメモ。
ブラウザの画面上をクリックした際に、クリック位置にある要素の重なり的に下にある要素を取得する必要があったので。
JQuery使用。

1.クリックした位置を取得する
2.クリックした位置の祖先ノードを取得する
3.祖先ノードのクリックしたい位置にある要素をelementFromPointで全て取得する
4.3で取得した要素から目的の要素を探して、操作を加える

        protected clickEvent(event: Event) {
            let hiddenElementList = [];
            const mouseLeft = event.pageX;
            const mouseTop = event.pageY;
            // クリックしたコメントが所属するノードの一番祖先のノードのdocumentを取得する
            const ownerDocument = $(event.currentTarget)[0].ownerDocument;
            let overlapElement: HTMLElement = null;
            // mousedownした位置にあるすべての要素とその要素のvisibilityの設定を確保する
            for (let checkTarget: HTMLElement = null; checkTarget !== ownerDocument.documentElement; checkTarget = overlapElement) {
                // 指定したウインドウ上の位置にあるHTMLElementを取得する(重なりの一番上の要素が取得される。visibilityがhiddenの要素は取得されない)
                overlapElement = <HTMLElement>ownerDocument.elementFromPoint(mouseLeft, mouseTop);
                if (overlapElement === null && overlapElement !== undefined && overlapElement !== checkTarget) {
                    hiddenElementList.push({
                        Element: overlapElement,
                        Visibility: overlapElement.style.visibility
                    });
                    overlapElement.style.visibility = "hidden";
                    continue;
                }
                break;
            }
            // mousedownした位置にあるすべての要素をから目的の要素を探す
            hiddenElementList.forEach((value, index: number) => {
                let element = value.Element;
                element.style.visibility = value.Visibility;
                // ここで条件で検索する。例えばidとか
                if($(element).attr("id") === "") {
                    // ここで目的の要素を操作する。
                }
            });
        }

こんな方法もあるよーという意見がほしいです。
以上。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1