在过去的两天里,我一直试图通过大量不同的材料组件库来解决这个问题 . 我已经尝试过Material Design Lite,它根本没有显示任何Snackbar,在转移到material-components-web之后我得到了Snackbar来显示,尽管它只是在它再次消失之前的一瞬间 . 我想在这种情况下使用它作为cookie同意栏,我知道有比使用Snackbars更好的方法,我仍然想学习如何使用它们 .
我的HTML如下(缩减了很多):
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css">
<script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</head>
<body>
<!-- HTML -->
<div class="mdc-snackbar" id="cookie-consent-bar" aria-live="assertive" aria-atomic="true" aria-hidden="true">
<div class="mdc-snackbar__text"></div>
<div class="mdc-snackbar__action-wrapper">
<button type="button" class="mdc-snackbar__action-button"></button>
</div>
</div>
<script src="js/cookies.js"></script>
</body>
</html>
cookies.js文件如下所示:
const MDCSnackbar = mdc.snackbar.MDCSnackbar;
const MDCSnackbarFoundation = mdc.snackbar.MDCSnackbarFoundation;
$(function () {
if (!getCookie('cookieConsent')) {
const snackbar = new MDCSnackbar(document.querySelector('.mdc-snackbar'));
var cookieMsgHandler = function(event) {
document.cookie += "consent_cookies=true; expires=Sun, 28 Jul 2030 12:00:00 UTC";
};
const data = {
message: 'This website uses Cookies. By continuing to use it you agree to its use of cookies. Read more at the Cookie Policy.',
timeout: 99999999,
actionHandler: cookieMsgHandler,
actionText: 'Accept'
};
snackbar.show(data);
}
});
function getCookie(cname) { // YES, this is from W3schools, it's a good method alright
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return null;
}
关于这个文件的几句话:
-
页面加载完毕后应该运行
-
它检查以前被解雇的cookie,如果没有,则进入代码路径 . 它进入了这个阶段 .
-
我试过这个有和没有超时选项,无济于事 .
每当我进行硬刷新时,快餐栏很快出现在屏幕的底部,然后再次消失 . 我希望它留在页面上......
在此先感谢您的帮助 .