1 回答

TA貢獻1799條經(jīng)驗 獲得超9個贊
對我來說,問題似乎是尋找特定點的元素。如果是這樣你可以使用document.elementFromPoint()
.
let x = 10;
let y = 140;
let el = document.elementFromPoint(x, y);
el.style.background = "red";
// or $(el).css("background", "red");
<ul>
? ?<li>first list</li>
? ?<li>second list</li>
? ?<li>third list</li>
</ul>
<h3>Skills:</h3>
<p>This are my skills. xyz, abc, pqr</p>
如果您只想通過頂部偏移量,例如因為您不想指定坐標(biāo)x,則必須遍歷您的元素。
紅線顯示要檢查的頂部偏移。添加并返回該行之前和之后的所有元素。它們以藍色背景顯示。
/**
?* Get all children that start before `offset_top` and end after?
?* `offset_top`.
?*
?* @param {(HTMLElement|jQuery|string)} parent?
?*? ? The parent as the element or as the selector
?* @param {number} offset_top
?*? ? The top offset to check
?*
?* @return {jQuery}
?*? ? All elements that are on the specific location.
?*/
function findChildrenWithOffset(parent, offset_top){
? let found = $([]);
? $(parent).children().each(function(){
? ? let t = $(this);
? ? let o = t.offset();
? ? let start = o["top"];
? ? let end = start + t.outerHeight();
? ? if(start <= offset_top && offset_top <= end){
? ? ? found = found.add(t);
? ? }
? ? if(t.children().length > 0){
? ? ? t.children().each(function(){
? ? ? ? found = found.add(findChildrenWithOffset(this, offset_top));
? ? ? });
? ? }
? });
??
? return found;
}
let c = findChildrenWithOffset(document, 140);
$(c).css("background", "rgba(0, 0, 255, 0.2)");
.absolute{
? position: absolute;
? height: 20px;
? width: 20px;
? border: 1px solid green;
}
.offset-line{
? position: absolute;
? top: 139px;
? left: 0;
? right: 0;
? background: red!important;
? height: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
? ?<li>first list</li>
? ?<li>second list</li>
? ?<li>third list</li>
</ul>
<h3>Skills:</h3>
<p><span style="text-decoration: underline;">This</span> are my skills. xyz, abc, pqr</p>
<div class="absolute" style="left: 220px; top: 110px;">
? A1
</div>
<div class="absolute" style="left: 240px; top: 120px;">
? A2
</div>
<div class="absolute" style="left: 260px; top: 130px;">
? A3
</div>
<div class="absolute" style="left: 280px; top: 140px;">
? A4
</div>
<div class="absolute" style="left: 300px; top: 150px;">
? A5
</div>
<div class="offset-line"></div>

TA貢獻1719條經(jīng)驗 獲得超6個贊
無法查詢應(yīng)用了特定樣式的元素。您可以查詢頁面中的所有元素并循環(huán)遍歷它們,檢查它們的樣式,但這會導(dǎo)致大量開銷。
不過,如果您可以根據(jù)父元素、類型等縮小可能的元素范圍,那么這可能是可行的。
添加回答
舉報