用js怎么实现一个div显示时间2秒后就自动消失。

JavaScript066

用js怎么实现一个div显示时间2秒后就自动消失。,第1张

首先,需要一个定时器,可以使用JS中的setTimeout() 方法。

其次,实现DIV消失,有很多种办法,可以使用$("#div").css('display','none'),通过设置DIV的display属性为none实现隐藏,也可以使用Jquery中hide()方法实现隐藏,还可以使用remove()移除DIV来实现DIV的消失。

下面是使用css(),setTimeout() 两个方法实现2秒后自动消失的完整代码:

扩展资料:

clearTimeout()用于重置js定时器,如果你希望阻止setTimeout的运行,就可以使用clearTimeout方法。

例如,如果想手动点击按钮停止DIV消失,代码可以这样写:

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>实现DIV2秒后就自动消失</title>

<script src="__JS__/jquery.min.js"></script>

</head>

<body>

<div id="div">

这是DIV里的内容

</div>

<a id="stop" onclick="stop()"/>点击停止消失</a>

<script>

var timer

$(function () {

timer=setTimeout(function () {

$("#div").css('display','none')

}, 2000)

})

function stop(){

clearTimeout(timer)

}

</script>

</body>

</html>

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8"/>

<title>定时弹窗</title>

<style type="text/css">

html,body{

width:100%

height:100%

margin:0

padding:0

}

.box{

width:100%

}

.tc-box{

width:25%

margin:80px auto

border:1px solid #f00

text-align: center

line-height: 150px

}

</style>

</head>

<body>

<div class="box">

<div class="tc-box" id="tc">

<div class="tc-cont">我是弹窗内容</div>

<button id="btn">点击关闭</button>

</div>

</div>

<script type="text/javascript">

var btn = document.getElementById('btn')

btn.onclick = function(){

var tc = document.getElementById('tc')

tc.style.display = 'none'

}

function xs(){

var tc = document.getElementById('tc')

tc.style.display = 'block'

console.log('aaaaaaa')

}

var lia = window.setInterval(xs,5000)

</script>

</body>

</html>

点击关闭之后5秒就会自动弹出

上面的代码有点不太合理,下面代码优化了一下。

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8"/>

<title>定时弹窗</title>

<style type="text/css">

html,body{

width:100%

height:100%

margin:0

padding:0

}

.box{

width:100%

}

.tc-box{

width:35%

margin:80px auto

border:1px solid #f00

text-align: center

line-height: 150px

}

</style>

</head>

<body>

<div class="box">

<div class="tc-box" id="tc">

<div class="tc-cont">我是弹窗内容</div>

<button id="btn">点击关闭5秒后继续弹出</button>

<button id="btn1">点击关闭,不再弹窗</button>

</div>

</div>

<script type="text/javascript">

var btn = document.getElementById('btn')

function xs(){

var tc = document.getElementById('tc')

tc.style.display = 'block'

tc.classList.remove('on')

console.log('aaaaaaa')

}

btn.onclick = function(){

var tc = document.getElementById('tc')

tc.style.display = 'none'

var lia = window.setInterval('xs()',5000)

tc.classList.add('on')//添加一个on类

if(tc.classList.contains('on') == true){ //查询类

function dsq(){

window.clearInterval(lia)

}

window.setTimeout(dsq,5000)

}

}

// 清除定时器

var btn1 = document.getElementById('btn1')

btn1.onclick = function(){

var tc = document.getElementById('tc')

tc.style.display = 'none'

}

</script>

</body>

</html>

因为一直弹窗会对浏览器产生很大的负荷,这里除了添加不再弹窗之外还优化了一下代码。

之前的代码是点击之后开始执行循环函数,但是不停止循环,不管弹窗是否显示的状态都会每5秒执行一次,这样明显不合理,应该是在你关闭弹窗之后5秒才执行。弹窗在显示状态不执行。