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

JavaScript09

用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>

一般的处理方式是在前台通过JS控制,JS控制显示时间的代码如下,各种不同的显示方式:

[javascript]

function Clock() {

var date = new Date()

this.year = date.getFullYear()

this.month = date.getMonth() + 1

this.date = date.getDate()

this.day = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")[date.getDay()]

this.hour = date.getHours() <10 ? "0" + date.getHours() : date.getHours()

this.minute = date.getMinutes() <10 ? "0" + date.getMinutes() : date.getMinutes()

this.second = date.getSeconds() <10 ? "0" + date.getSeconds() : date.getSeconds()

this.toString = function() {

return "现在是:" + this.year + "年" + this.month + "月" + this.date + "日 " + this.hour + ":" + this.minute + ":" + this.second + " " + this.day

}//现在是<span id="clock">现在是:2013年3月6日 13:54:17 星期三</span>

[javascript]

<span></span>

this.toSimpleDate = function() {

return this.year + "-" + this.month + "-" + this.date

}//2013-03-06

this.toDetailDate = function() {

return this.year + "-" + this.month + "-" + this.date + " " + this.hour + ":" + this.minute + ":" + this.second

}//2013-03-06 13:45:43

this.display = function(ele) {

var clock = new Clock()

ele.innerHTML = clock.toString()//显示方式调用

window.setTimeout(function() {clock.display(ele)}, 1000)

}

}

1、首先要引入js文件 2、指定的元素调用js的方法 /* 下面的例子是JQuery的方法调用 each遍历函数,mouseenter函数,find函数*/ $(function () { $(".course-side .big-course").each(function () { $(this).mouseenter(function () { $(this)