首先在body标签上面添加横幅的html代码,通过设置top banner的display:none 来实现 一开始网站加载时候隐藏横幅:
<div id="top-banner" style="display:none ;"> <a href="#"><img src="/path/to/banner.png" alt="" style="width:100%;"></a> <button id="close-button"></button> </div>
然后在css文件里面,添加横幅的css,来实现横幅和关闭符号的位置对应:
#top-banner {
position: fixed;
top: 0;
max-width: 1230px;
width:80%;
left: 50%;
transform: translateX(-50%);
background-color: #f1f1f1;
text-align: center;
z-index: 999;
}
.admin-bar #top-banner {
top: 32px;
}
#close-button {
position: absolute;
top: 10px;
right: 10px;
}
#close-button::before {
content: "";
background-image: url(../images/close.svg);
background-repeat: no-repeat;
background-size: contain;
width: 1em;
height: 1em;
display: inline-block;
margin-right: 0.5em;
}
上面css设置了横幅在浏览器的最上方固定,设置了最大宽度为1230, 宽度为80%, 使用left50%加上transform:translatex 方法来实现居中,加上z-index:999 来实现覆盖到最顶层。通过设置top banner为position:relative 和设置close button 为position absolut 来实现关闭的icon位于图片的右上角。(设置图片的宽度为100%)。通过设置::before属性来实现图片添加icon。
接下来通过javascript来实现网站加载时候更改top banner的style为display:block,
document.getElementById("top-banner").style.display = "block";
然后通过点击关闭按钮,来实现style变为display:none.
document.getElementById(“close-button”).addEventListener(“click”, function () {
document.getElementById(“top-banner”).style.display = “none”;
});
当然,你还可以设置添加cookie等方式,来实现用户关闭一次后,多久时间内不再重复出现广告。