微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 等待元素显示给用户

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

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

解决方法

这有点混乱,你想尝试简单的“睡眠”吗?

您可以使用以下命令等待元素

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>

如果你想等待时间,因为你已经设置了函数和选择器,它应该出现在这个时间之后.你可以考虑一个简单的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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐