我希望在屏幕底部出现一个警报,表明该网站正在使用 cookie(并且只需向新用户显示)。如果您也向下滚动,它需要停留在底部。我不知道该怎么做,因为我是一个自学的人,我刚刚开始学习如何编码。 感谢您的帮助。
我们需要将警报面板添加到页面底部。为了设置这个面板的样式,我们应该使用 CSS。该面板还有确认按钮。当用户单击确认按钮时,我们会在浏览器中设置一个 cookie,并且不再显示面板。
<div class="bottom" id="alert">
This website uses cookies
<button onclick="accpetCookie()">
Click here to accept cookies
</button>
</div>
<div class="scroll">
website content
</div>
这是 CSS 类的样式:
.bottom {
position: fixed;
bottom: 0;
width: 100%;
background: #ccc;
color: #fff
}
.scroll {
min-height: 1500px;
}
<script>
// if user has already checked the confirmation button
// the alert panel should be hidden.
if (getCookie('accepted') === 'yes') {
document.getElementById("alert").style.display = "none";
}
// user clicks the confirmation ->
// set a cookie with name: 'accepted' and value: 'yes'
function accpetCookie() {
setCookie('accepted', 'yes', 100);
}
// code from: http://stackoverflow.com/a/4825695/191220
// set cookie method
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) +
((exdays == null)
? ""
: "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
// get cookie method
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
</script>
查看JsFiddle页面进行现场演示。