等待元素显示给用户

时间:2016-10-03 22:22:01

标签: javascript jquery

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

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

2 个答案:

答案 0 :(得分:1)

有点混乱,你在尝试一个简单的睡眠&#34;?

您可以使用以下方式等待元素加载:

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

一些工作代码段,运行它:

&#13;
&#13;
// 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);
}
&#13;
#my_element{
  width: 100px;
  height: 100px;
  background-color: red;
  display: none; /* INVISIBLE */
}
&#13;
<div id="my_element"></div>
&#13;
&#13;
&#13;

如果您要等待设置为该功能的time以及selector之后应显示的time ..您可以介意一个简单的setTimeout()和CSS。

运行下面的示例,希望它有所帮助:

&#13;
&#13;
// 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);
  }
}
&#13;
#my_element{
  width: 100px;
  height: 100px;
  background-color: red;
  display: none; /* INVISIBLE */
}
&#13;
<div id="my_element"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以使用jQuery .ready()

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