这是我在 stackoverflow 上的第一篇文章!
我创建了 css 来在两种不同的背景颜色之间转换。
.body {
font-family: Tahoma, Geneva, sans-serif;
font-size: 20px;
font-weight: bold;
color: #999;
transition: background 5s;
webkit-transition: background 5s;
}
.bodyclick {
background-color:#333
}
它适用于照片库类型页面,我喜欢有不同的背景选项来查看图像。当单击“项目名称”类的对象时,我还使用 javascript/jQuery 在两种颜色之间进行转换,并将当前背景状态存储在 cookie 中,以便当您浏览不同页面时背景颜色将保持不变。
// toggles 'bodyclick' class on the body based on the click of an object with the class projectname and sets the state in a cookie
$(document).ready(function() {
var button = $('.projectname');
//check the cookie when the page loads
if ($.cookie('currentToggle') === 'hidden') {
toggleBackground(button, false);
}
else {
toggleBackground(button, true);
}
//handle the clicking of the background (projectname) toggle button
button.click(function() {
//toggle the background as required, base on current state
if ($('.body').hasClass('bodyclick')) {
toggleBackground($(this), true);
}
else {
toggleBackground($(this), false);
}
});
});
function toggleBackground(button, show) {
var background = $('.body');
if (show) {
background.removeClass('bodyclick');
$.cookie('currentToggle', '', { path: '/' });
}
else {
background.addClass('bodyclick');
$.cookie('currentToggle', 'hidden', { path: '/' });
}
};
我现在遇到的唯一问题是,当 cookie 设置为深灰色并且您刷新或导航到单独的页面时,它会在页面加载时从默认颜色(白色)转换为深灰色,而不仅仅是保持不变。如果我从 CSS 中删除过渡属性,它会立即加载到我想要的颜色,但我喜欢单击更改背景时的过渡效果。
如果您想实时观看,可以访问此page
然后单击右下角“消费后”文本以更改颜色,然后刷新或导航到其他页面。
让我知道如何仅在单击时而不是在页面加载时进行此转换,或者如果我需要更好地澄清我的问题。
也作为一个附带问题。谁能解释一下我的 javascript 中的“隐藏”和“显示”值在做什么?我是编程新手,我从 stackoverflow 帖子中借用了代码,并对其进行了修改以实现我需要的功能,但我不完全理解这些值是如何工作的。
最佳答案
添加和删除第二个类,它会覆盖第一个类的转换:
.no-transition {
transition: all 0s !important;
-webkit-transition: all 0s !important;
}
JS:
background.addClass('no-transition').addClass('bodyclick').removeClass('no-transition');
关于javascript - 从 cookie 加载 CSS 类(带有转换),而不转换到它们中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16615273/