在元素加载之前更改CSS

问题描述 投票:0回答:1

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

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

任何人都可以想出一种方法让导航栏从页面到页面记住它的状态AND(当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>
javascript jquery css dom cookies
1个回答
-1
投票

如果在新页面菜单中--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>
© www.soinside.com 2019 - 2024. All rights reserved.