Wait for element to be displayed to user

How do I wait for an element to be displayed/seen by the user? I have the following function, but it only checks to see if the element exists and not whether it is visible to the user.

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);
    }
}

It's a bit confuse, are you trying a simple "sleep"?

You can wait element load using:

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

Some working snippet, run it:

// 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>

你可以使用jQuery .ready()

selector.ready(function(){
  // do stuff
})
链接地址: http://www.djcxy.com/p/83542.html

上一篇: 如何获得jQuery中可见列表的eq?

下一篇: 等待元素显示给用户