HTML代码
<div id="banner">
<p>This is a self-closing banner.</p>
<button id="close-banner">X</button>
</div>
css代码
#banner {
background-color: #f1f1f1;
padding: 10px;
position: fixed;
bottom: 0;
left: 0;
width: 100%;
text-align: center;
z-index: 999;
}
#close-banner {
position: absolute;
top: 10px;
right: 10px;
background-color: #f44336;
color: white;
font-weight: bold;
padding: 5px 8px;
border-radius: 50%;
cursor: pointer;
}
Javascript代码
// set a timeout to close the banner after 3 seconds
setTimeout(function(){
var banner = document.getElementById("banner");
banner.style.display = "none";
}, 3000);
// add an event listener to the close button
var closeButton = document.getElementById("close-banner");
closeButton.addEventListener("click", function() {
var banner = document.getElementById("banner");
banner.style.display = "none";
});
JavaScript使用setTimeout函数在3秒(3000毫秒)后关闭横幅,方法是将横幅元素的显示属性设置为“none”。它还使用addEventListener将一个单击事件附加到关闭按钮,该按钮也通过在单击时将banner元素的显示属性设置为“none”来关闭横幅。