簡體   English   中英

使用document.elementFromPoint檢查特定坐標處的元素是否具有特定類

[英]Use document.elementFromPoint to check if an element at specific co-ordinates has a particular class

我有座標。 我想檢查這些坐標處是否存在具有特定類的元素。 我該怎么做?

我已經嘗試了以下代碼(這是一個jsfiddle: https ://jsfiddle.net/0o160f5g/2/):

HTML:

<div class="foo"></div>

CSS:

.foo{
    width: 100px;
    height: 100px;
    background-color: red;
}

JS:

if(document.elementFromPoint(30, 30) == ".foo"){
    alert("The red square is within the coordinates")
}else{
    alert("The red square is outside the coordinates")
}

該代碼應發出警報“紅色方塊在坐標內”。 但是,它會發出警告“紅色方塊在坐標之外”。 我該如何解決?

elementFromPoint返回一個Element對象(或null),而不是css選擇器。 因此,您將測試該元素的各種屬性,以查看其是否匹配

//checks class
document.elementFromPoint(30,30).classList.contains('foo')
//checks id
document.elementFromPoint(30,30).id == 'foo'
//test for null first so not to get type errors 
var eleAtPoint = document.elementFromPoint(30,30);
if(eleAtPoint && eleAtPoint.classList.contains("foo")){
   //do something.
}

或者,如果您已經有了一個元素,請將您已有的引用與elementFromPoint的結果進行比較

var elementToCheck = document.querySelector('.foo');

if(document.elementFromPoint(30,30) === elementToCheck){
  //do something.
}

Document接口的elementFromPoint()方法返回指定坐標處的最頂層元素。

您應該將此與另一個元素進行比較:

   if(document.elementFromPoint(30, 30) == document.getElementsByClassName('foo')[0]){
        alert("The red square  is within the coordinates")
    }else{
        alert("The red square is outside the coordinates")
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM