首页 > 解决方案 > 在元素加载之前更改 CSS

问题描述

目标:我有一个主导航栏,单击时会打开(使用 jquery 和 css 样式--active)。如果用户将其保持打开状态并导航到站点上的新页面,则导航栏需要保持打开状态,而不是首先看起来是关闭的。

--active问题:导航栏确实保持打开状态(使用 cookie 来记住其状态),但在采用类之前以默认样式(即关闭)简要地看到。看起来很笨重,就像一个快速的闪光灯。

任何人都可以想出一种方法来让导航栏在页面之间记住它的状态并且(当 cookie 被“打开”时)采用--active类样式而不简要显示默认样式?

(我看过How to change CSS property before element is created?,但它对我不起作用)。

$(document).ready(function() {
  const menuButton = $('.header__menu-button');
  const menuState = Cookies.get('menuState');

  if (menuState == 'opened') {
    menuButton.addClass('--active');
  };

  menuButton.on('click', function() {
    $(this).toggleClass('--active');

    if (menuButton.hasClass('--active')) {
      Cookies.set('menuState', 'opened');
    } else {
      Cookies.set('menuState', 'closed');
    }
  });
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: #dcdcdc;
}

.header {
  height: 110px;
  background-color: #add8e6;
}

.header__button-container {
  display: flex;
  justify-content: flex-end;
}

.header__menu-button {
  min-width: 100px;
  height: 110px;
  background-color: #fff;
  color: #000;
}

.menuTransition {
  transition: all 1s ease-in-out;
}

.header__menu-button.--active {
  min-width: 250px;
  background-color: #000;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header">
  <div class="header__button-container">
    <button class="header__menu-button menuTransition"></button>
  </div>
</div>

标签: javascriptjquerycssdomcookies

解决方案


如果在新页面菜单中--active使用此代码之前$(document).ready(function()

$("button.header__menu-button").removeClass("--active");

此代码--active从您的导航栏中删除类!在你看到页面之前。

$(document).ready(function() {
  $("button.header__menu-button").click(function() {
    $(this).toggleClass("--active");
  })
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: #dcdcdc;
}

.header {
  height: 110px;
  background-color: #add8e6;
}

.header__button-container {
  display: flex;
  justify-content: flex-end;
}

.header__menu-button {
  min-width: 100px;
  height: 110px;
  background-color: #fff;
  color: #000;
}

.menuTransition {
  transition: all 1s ease-in-out;
}

.header__menu-button.--active {
  min-width: 250px;
  background-color: #000;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<div class="header">
  <div class="header__button-container">
    <button class="header__menu-button menuTransition"></button>
  </div>
</div>


推荐阅读