2016-10-03 90 views
4

如何等待元素被用户显示/看到?我有以下功能,但它只检查元素是否存在,而不检查它是否对用户可见。等待元素显示给用户

function waitForElementDisplay (selector, time) { 
    if (document.querySelector(selector) != null) { 
     return true; 
    } else if (timeLimit < timeSince) { 
     return false; 
    } else { 
     timeSince += time; 
     setTimeout(function() { 
      waitForElementDisplay(selector, time, timeLimit, timeSince); 
     }, time); 
    } 
} 
+0

的可能的复制[检测元素是否可见](http://stackoverflow.com/questions/8774089/detect-if-an-element-is-visible) – vlaz

+0

它还有另一件事[这里](http:// stackov erflow.com/questions/16255423/finding-if-element-is-visible-javascript)和[这里](http://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom ) – vlaz

+3

define *“对用户可见”* ..可以通过多种方式解释 – charlietfl

回答

1

这有点混乱,你是在尝试一个简单的“睡眠”吗?

可以使用等待元素负载:

document.querySelector(selector).onload = function() { 
    // Your code ... 
} 

一些工作片段,运行它:

// Triggering load of some element 
 
document.querySelector("body").onload = function() { 
 
    // Setting the timeout and visible to another element 
 
    setTimeout(function() { 
 
     document.querySelector("#my_element").style.display = "block" /* VISIBLE */ 
 
    }, 1000); 
 
}
#my_element{ 
 
    width: 100px; 
 
    height: 100px; 
 
    background-color: red; 
 
    display: none; /* INVISIBLE */ 
 
}
<div id="my_element"></div>

如果你想等待time因为你已经设置为功能和selector这应该出现在这之后time ..你可以介意ab出一个简单的setTimeout()和CSS。

运行下面的例子,希望它有助于:

// Triggering, in my exemple i've used: WINDOW ONLOAD 
 
window.onload = function() { 
 
    waitForElementDisplay("#my_element", 1000); 
 
} 
 

 
function waitForElementDisplay (selector, time) { 
 
    // Check the DOM Node in console 
 
    console.log(document.querySelector(selector)); 
 
    
 
    // If it's a valid object 
 
    if (typeof document.querySelector(selector) !== "undifined") { 
 
    
 
    // Setting the timeout 
 
    setTimeout(function() { 
 
     document.querySelector(selector).style.display = "block" /* VISIBLE */ 
 
    }, time); 
 
    } 
 
}
#my_element{ 
 
    width: 100px; 
 
    height: 100px; 
 
    background-color: red; 
 
    display: none; /* INVISIBLE */ 
 
}
<div id="my_element"></div>

0

您可以使用jQuery。就绪()

selector.ready(function(){ 
    // do stuff 
})