现在,我正在使用 switchClass 来更改正文背景。变化是即时的,而且对眼睛来说并不容易。
$('.Click').click(function () {
var thisClass = $(this).attr('class');
var st = thisClass.split(' ');
var firstClass = st[0];
if (firstClass == "item1") {
$('.mask').animate({
marginLeft: "-100%"
}, 600, function () {
$("body").switchClass($("body").attr("className"), "bg1");
});
} else if (firstClass == "item2") {
$('.jobsMask').animate({
marginLeft: "-200%"
}, 600, function () {
$("body").switchClass($("body").attr("className"), "bg2");
});
}
});
如何设置动画/使其不那么突然?
最佳答案
对于背景颜色
淡入淡出:
您可以在 body
元素上使用过渡来为 background
属性的更改添加动画效果,如下所示:
body {
-ms-transition: background 0.8s ease 0s;
-moz-transition: background 0.8s ease 0s;
-o-transition: background 0.8s ease 0s;
-webkit-transition: background 0.8s ease 0s;
transition: background 0.8s ease 0s;
}
测试一下:http://jsbin.com/odabit/2/edit
对于淡入淡出的背景图像:
过渡似乎不适用于 background-image
(编辑:它们在 Chrome 中工作,但在 Fx16、Opera12.1 或 IE9 中不起作用),所以我的解决方法是将你的背景图像位于单独的 div 上,然后淡入淡出,如下所示:http://jsbin.com/odabit/7/edit
切换代码如下所示:
var cls1 = 'bg1', cls2 = 'bg2',
body = $('body'),
bg1 = body.hasClass(cls1) || !!body.children('.'+cls1)[0],
bg = bg1 ? body.children('.'+cls1) : body.children('.'+cls2),
newBg;
if (!bg[0]) {
bg = $('<div>', {'class': (bg1 ? cls1 : cls2)}).prependTo(body);
}
newBg = $('<div>', {'class': (bg1 ? cls2 : cls1)}).insertAfter(bg).hide();
body.removeClass(cls1 +' ' +cls2);
bg.fadeOut('slow', function() { bg.remove(); });
newBg.fadeIn('slow');
以及支持它的 CSS:
body > div[class^="bg"] {
position: fixed;
top: 0; right: 0; bottom: 0; left: 0;
z-index: -1;
}
.bg1 {
background: url(/* image 1 */);
}
.bg2 {
background: url(/* image 2 */);
}
关于javascript - 使用 jquery 在点击时淡入 body 背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13276770/