javascript - 在元素加载之前更改 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>
解决方案
如果在新页面菜单中--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>
推荐阅读
- python - 如何从这些跨度标签之间刮取数据?
- python - Python 在命令行上不再在虚拟环境中找到模块
- java - 我是否正确设置了此 BST?如果是这样,我该如何在其他方法中使用它?
- mysql - 当我有单个逗号和 | 时,您的 SQL 语法有错误。
- java - 在 netty 中对 LengthFieldBasedFrameDecoder 进行更多控制
- html - 使用 v-for 和 bootstrap 时卡片未形成网格
- swift - 检测应用程序是否在 macOS 测试版上运行
- tensorflow - 将具有 2 个输入的 keras 模型转换为 tflite 时出错
- css - 如何避免在浏览器记录的输入中丢失样式
- twitter-bootstrap - 引导程序和 Grails 3