![](/img/trans.png)
[英]In jQuery (or Javascript), how do I get the “topmost” element?
[英]How do i get the link of the topmost positioned image in a website?
我正在編寫一個腳本,該腳本需要在任何網站上位於最高位置的圖像的src,而不是源中的第一張圖像,而是位於最高位置的圖像。
我嘗試了一些非常基本的操作,即檢索第一個圖像標簽,但是這不適用於css / jquery / javascript定位的圖像。
所以任何想法我怎么能做到這一點? |----------------- | .....title.... | |------| | |image | <==== link needed | |------| |//text content |Lorem dolor ipsum
我不確定jQuery的答復,但我相信那仍然只會給您相對的圖像坐標。 在此之前的帖子中顯示了一種獲取頁面上html元素的絕對x,y坐標的方法,並從PrototypeJS竊取了相同的方法之后,以下代碼應該可以滿足您的要求,
請注意,我認為可以安全地使用0 top檢查來確定圖像是否不可見,但這可能是有問題的。 同樣,這只會在img標簽中獲取圖像,而不會獲取圖像鏈接或使用CSS設置的任何內容。
// cumulative offset function stolen from PrototypeJS
var cumulativeOffset = function(element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top: top,
left: left
};
};
// get all images
var results = document.getElementsByTagName("img");
var images = [];
for (result in results) {
if (results.hasOwnProperty(result)) {
images.push(results[result]);
}
}
// map our offset function across the images
var offsets = images.map(cumulativeOffset);
// pull out the highest image by checking for min offset
// offset of 0 means that the image is invisible (I think...)
var highest = images[0];
var minOffset = offsets[0];
for (i in offsets) {
if (minOffset.top === 0 ||
(offsets[i].top > 0 && offsets[i].top < minOffset.top)) {
minOffset = offsets[i];
highest = images[i];
}
}
// highest is your image element
console.log(highest);
您需要比較每個元素的.y
屬性。
function getTopMostImage() {
//Get all images
var imgs = document.querySelectorAll("img");
//Define a variable that marks the topmost image
var topmost = imgs[0];
//Check all image positions and mark the topmost
for (i = 1; i < imgs.length; i++) {
if (topmost.y > imgs[i].y)
topmost = imgs[i];
}
return topmost.src;
}
加載后,您可以通過first()檢查Dom中存在的第一個img元素。文檔在這里希望對您有所幫助
// Use the most appropriate selector for your images such as "body img" or bla bla...
var images = jQuery('img');
var topMostImageIndex = 0;
for (var i = 0; i < images.length; i++) {
if (jQuery(images[i]).position().top < jQuery(images[topMostImageIndex]).position().top) {
topMostImageIndex = i;
}
}
// It's the top-most image
images[topMostImageIndex];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.