带有Material Components Web的小吃店不断消失

时间:2018-07-28 08:54:40

标签: javascript snackbar material-components-web

过去2天,我一直在尝试使用大量不同的材料组件库来解决此问题。我尝试了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,如果没有,则进入代码路径。到了这个阶段。
  • 无论是否有超时选项,我都尝试过,但无济于事。

每当我进行一次强制刷新时,小吃栏都会很快出现在屏幕底部,然后再次消失。我希望它保留在页面上...

在此先感谢您的帮助。

0 个答案:

没有答案