替换(淡入)主体背景而不影响嵌套元素

Replace(fade) body backgrounds without effecting nested elements

本文关键字:影响 嵌套 元素 背景 淡入 主体 替换      更新时间:2023-09-26

点击时背景更改为图像或颜色。为了做到这一点,首先我为身体做了两个类:

body.bg-color {
    background-color:red;
}
body.bg-img {
    background: url(../images/bg.jpg) no-repeat center 0 fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

然后使用CCD_ 1和CCD_。事情是,这种方法褪色,除了背景,还有内容。应该做些什么来只淡入/淡出背景?

$(document).ready(function(){
$('body').addClass('bg-color');
$('.element,#content1,#content2').hide();
    $("#link1").click(function(){
        $('#wrapper').hide();
        $('body').removeClass('bg-color').fadeOut();    
        $('body').addClass('bg-img').fadeIn();
    });
    $("#link2").click(function(){
        $('#wrapper').show();
        $('body').removeClass('bg-img').fadeOut();
        $('body').addClass('bg-color').fadeIn();
    });
});

不要将这些全部应用于body标记,而是使用高度和宽度为100%的固定位置<div>,并为其提供背景色,这样您就可以淡出该元素而不是整个元素。

此外,您可以只切换一个类,而不是同时添加和删除两个类。

例如。

#bg{
    position: fixed;
    height: 100%;
    width: 100%;
    z-index: 1;
    background: red;
}
#bg.bg-img {
    background: url(../images/bg.jpg) no-repeat center 0 fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

只需将以下内容放在打开的正文标签后面:

<div id="bg"></div>

这是您更新的JS:

$(document).ready(function(){
    $('.element,#content1,#content2').hide();
    $("#link1").click(function(){
        $('#wrapper').hide();
        $('#bg').fadeOut().addClass('bg-img').fadeIn();
    });
    $("#link2").click(function(){
        $('#wrapper').show();
        $('#bg').fadeOut().removeClass('bg-img').fadeIn();
    });
});