當前位置:編程學習大全網 - 源碼下載 - 求壹段js代碼打開頁面div5秒彈出,點擊關閉按鈕後再次定時彈出

求壹段js代碼打開頁面div5秒彈出,點擊關閉按鈕後再次定時彈出

<!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秒才執行。彈窗在顯示狀態不執行。

  • 上一篇:壹個電商APP開發成本到底多少錢(壹個app的開發成本要多少錢)
  • 下一篇:為什麽罪惡都市的秘籍有不了啊?請高手回答,絕非記錯秘籍
  • copyright 2024編程學習大全網