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>

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...