加载页面超时

时间:2013-06-22 10:16:49

标签: javascript html css

如何使用html和javascript将此场景放入代码中?

如果加载屏幕的时间小于10秒,则启用显示输入字段的css代码,否则如果加载屏幕后的时间大于10秒,则禁用显示输入字段的css代码?

基本上我想显示和输入字段十秒钟然后让它消失。

1 个答案:

答案 0 :(得分:2)

目前还不清楚你真正想做什么,但我猜你想要在用户到达页面后的前10秒内应用一些CSS,然后在此之后关闭。

一种简单的方法是从body元素开始:

<body class="first10">

...然后在您的文档末尾添加此脚本:

<script>
setTimeout(function() {
    document.body.className = ""; // removes the class
}, 10000); // 10000ms = 10 seconds
</script>

setTimeout计划在延迟后由JavaScript引擎运行的函数,以毫秒表示。在这种情况下,我们的函数会从body中删除所有类。如果您在body上有其他课程,您可能希望保留,您必须做一些稍微复杂的事情:

document.body.className = document.body.className.replace(/\bfirst10\b/, '');

或者同时拥有“first10”和“notfirst10”类可能更方便:

<script>
setTimeout(function() {
    document.body.className =
        document.body.className.replace(/\bfirst10\b/, '') +
        " notfirst10";
}, 10000); // 10000ms = 10 seconds
</script>

您希望应用于前10秒的CSS规则将如此定义:

body.first10 /* further selectors here */ {
    /* ...rules here... */
}

例如,这会将<p>元素中的文本转换为类foo蓝色,但仅限前10秒:

body.first10 p.foo {
    color: blue;
}

同样,这只会在前10秒内显示id "banner"的横幅广告:

body.notfirst10 #banner {
    display: none;
}

完整示例:Live Copy | Live Source

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>First 10 seconds...</title>
<style>
  #banner {
    background-color: blue;
    color: white;
    font-weight: bold;
  }

  body.first10 p.foo {
      color: blue;
  }

  body.notfirst10 #banner {
      display: none;
  }
</style>
</head>
<body class="first10">
  <div id="banner">This is the banner</div>
  <p class="foo">This is a 'foo' paragraph</p>
  <p>This is not a 'foo' paragraph</p>
  <script>
  setTimeout(function() {
      document.body.className =
          document.body.className.replace(/\bfirst10\b/, '') +
          " notfirst10";
  }, 10000); // 10000ms = 10 seconds
  </script>
</body>
</html>