jquery背景颜色淡入淡出滚动

时间:2022-11-04 19:05:47

I want the background of the header to fade in after a number of pixel scrolled. With the code below i kinda get it but not much right! Any idea? thanks!

我希望在滚动一些像素后,标题的背景会淡入。有了下面的代码我有点得到它但不太正确!任何想法?谢谢!

$(function () {
    $(window).scroll(function () {
        $(document).scrollTop() > 100 ? $('header').css({
            "background": 1
        }).fadeIn() : $('header').css({
            "background": 0
        }).fadeOut();
    });
})

6 个解决方案

#1


7  

A combination of Miquel Las Heras and Owen 'Coves' Jones's answers, who both submitted a not completely on-topic or not complete answer.

Miquel Las Heras和Owen'Coves'Jones答案的组合,他们都提交了一个不完全是主题或不完整的答案。

Use background trasitions (CSS3) and jQuery simultaneously.

同时使用后台trasition(CSS3)和jQuery。

JSFiddle

的jsfiddle

jQuery

jQuery的

$(document).ready(function () {
    $(window).scroll(function () {
        if ($(document).scrollTop() > 100) {
            $("header").addClass("scrolled");
        } else {
            $("header").removeClass("scrolled");
        }
    });
});

CSS

CSS

header {
    background-color:blue;
    -webkit-transition: background-color 700ms linear;
    -moz-transition: background-color 700ms linear;
    -o-transition: background-color 700ms linear;
    -ms-transition: background-color 700ms linear;
    transition: background-color 700ms linear;
}
header.scrolled {
    background-color: red;
}

Update February 3rd, 2017

browser support is very good, and the less performing jQuery solution below should not be used. Browser support.

浏览器支持非常好,不应该使用性能较差的jQuery解决方案。浏览器支持。

Cross-browser solution

If you want to make it more cross-browser compatible, you can try the color plugin. But from what I've tested, it has quite a bad performance. JSFiddle

如果您想使其更兼容跨浏览器,您可以尝试使用颜色插件。但是根据我的测试,它的性能相当糟糕。的jsfiddle

$(document).ready(function () {
    $(window).scroll(function () {
        if ($(document).scrollTop() > 100) {
            $("header").animate({
                backgroundColor: "red"
            }, 200);
        } else {
            $("header").animate({
                backgroundColor: "blue"
            }, 200);
        }
    });
});

Don't forget the plugin itself:

不要忘记插件本身:

//cdnjs.cloudflare.com/ajax/libs/jquery-color/2.1.2/jquery.color.js

#2


2  

I prefer to create 2 css classes for this type of issues. One for when window is scrolled and one for when it's not:

我更喜欢为这类问题创建2个css类。一个用于何时滚动窗口,一个用于何时不滚动:


    header { background: transparent; }
    header.scrolled { background: #f2f2f2; }

Then the javascript should be:

那么javascript应该是:


    $(function () {
      $(window).scroll(function () {
        if($(document).scrollTop()>100){
          $('header').addClass('scrolled');
        }
        else {
          $('header').removeClass('scrolled');
        }
      });
    })

#3


2  

First, as was mentioned in the other answer, you will need to include jQuery UI or the jQuery Color plugin for color animation.

首先,正如在另一个答案中提到的,您将需要包含jQuery UI或用于颜色动画的jQuery Color插件。

Second, and this is just winging it, but give this the old college try:

第二,这只是它的翼,但是给这个旧的大学尝试:

$(function(){
    $(window).scroll(function(){
        var $scrollPercent = ($(document).scrollTop() / 100);

        if($scrollPercent <= 1){
            $('header').css({backgroundColor:'rgba(0,0,0,'+$scrollPercent+')'});
        }
    });
});

This should give you a gradual fade in based on the amount down the page you scroll. This means that if you scroll 50 px down, your background color opacity would be set to 50% (50 px down / 100 px height wanted). You can also easily change the amount of height that you want to scroll down to reach full opacity very easily this way.

这应该会根据您滚动页面的数量逐渐淡出。这意味着如果向下滚动50像素,您的背景颜色不透明度将设置为50%(50 px向下/ 100 px高度需要)。您也可以通过这种方式轻松更改要向下滚动以达到完全不透明度的高度。

EDIT So it turns out you just want to fade in the color after 100px ... not my gradual fade in. No problem.

编辑所以事实证明你只想在100px之后淡出颜色...而不是逐渐淡入。没问题。

Others have pointed out the wonderful (and much better) CSS3 way to do it ... create a transition effect, and add a class on scroll. I won't steal their thunder, but I shall provide an alternative that works back to ancient browsers too.

其他人已经指出了这样做的奇妙(并且好得多)的CSS3方法......创建过渡效果,并在滚动上添加一个类。我不会偷他们的雷声,但我会提供一种可以回溯到古代浏览器的替代方案。

Add an additional line of HTML inside of your header at the top:

在顶部的标题内添加额外的HTML行:

<div class="header">
    <div class="headerBackground"></div>
    <!-- other header stuffs -->
</div>

Then set its CSS as such:

然后设置它的CSS:

.header {
    position:relative;
}

.headerBackground {
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    background-color:rgb(0,0,0);
    opacity:0;
    filter:alpha(opacity=0); // for IE8 and below
}

Then use the following jQuery:

然后使用以下jQuery:

$(function(){
    $(window).scroll(function(){
        var $bg = $('.headerBackground');

        if($(document).scrollTop() >= 100){
            $bg.animate({opacity:1},500); // or whatever speed you want
        } else {
            $bg.animate({opacity:0},500);
        }
    });
});

This also has the added benefit of not requiring another library (jQuery UI / jQuery Color plugin). The downside is, of course, the non-semantic HTML. Like I said, just another alternative.

这还有一个额外的好处,就是不需要另一个库(jQuery UI / jQuery Color插件)。当然,缺点是非语义HTML。就像我说的,只是另一种选择。

#4


0  

your code is correct, but jQuery does not natively support color animation. you need a plugin or jquery-ui for that: http://jqueryui.com/animate/

你的代码是正确的,但jQuery本身不支持颜色动画。你需要一个插件或jquery-ui:http://jqueryui.com/animate/

EDIT: actually, your code is kinda wrong. you want to set the backgroundColor to something. background: 1 is invalid css:

编辑:实际上,你的代码有点不对劲。你想将backgroundColor设置为某种东西。 background:1是无效的css:

so .css({'backgroundColor': 'red'}) and then .css({'backgroundColor': 'blue'})

所以.css({'backgroundColor':'red'})然后.css({'backgroundColor':'blue'})

#5


0  

If you don't need to support a lot of older browsers you can animate background colours with a combination of jQuery and css3 transitions:

如果您不需要支持许多旧版浏览器,可以使用jQuery和css3过渡组合为背景颜色设置动画:

Take the HTML:

拿HTML:

<div id="myBox">Stuff here</div>

And the javascript:

和javascript:

var myBox = $('#myBox');

myBox.on('click', function (el) {

    myBox.css('background-color', 'red');

}

Then click the element #myBox will change its background colour red. Instantly, with no fade.

然后单击元素#myBox将其背景颜色更改为红色。瞬间,没有褪色。

If you also put in place the css code:

如果您还放置了css代码:

#myBox {
    -webkit-transition: background-color 300ms ease-in-out;
    -moz-transition: background-color 300ms ease-in-out;
    transition: background-color 300ms ease-in-out;
}

Then any colour changes to the background will be faded over 300ms. Works on all latest version browsers, but not on IE 9 and below.

然后任何颜色变化到背景将褪色超过300毫秒。适用于所有最新版本的浏览器,但不适用于IE 9及更低版本。

#6


0  

The solution that I ended up using is as follows:

我最终使用的解决方案如下:

I created a section that I'm fading in and out based on the scroll position.

我创建了一个基于滚动位置淡入淡出的部分。

CSS

.backTex {
    width:100%;
    height:500px;
    margin-top:50px;
    background-color: @myGreen;
    //Height
    transition: height 0.5s ease;
    -webkit-transition: height 0.5s ease;
    -moz-transition: height 0.5s ease;
    -o-transition: height 0.5s ease;
    -ms-transition: height 0.5s ease;
    //Background-Color
    transition: background-color 0.5s ease;
    -webkit-transition: background-color 0.5s ease;
    -moz-transition: background-color 0.5s ease;
    -o-transition: background-color 0.5s ease;
    -ms-transition: background-color 0.5s ease;
    transition: background-color 0.5s ease;
} 

jQuery

$(document).scroll(function() {
        var positionScroll = $(this).scrollTop();

        if(positionScroll <= 499) {
            $(".backTex").css("background-color", "#fff");    
        } else if (positionScroll > 500 && positionScroll < 1100) {
            $(".backTex").css("background-color", "#2ecc71");
        } else {
            $(".backTex").css("background-color", "#fff");
        }
    });

As far as compatibility, I haven't noticed any issues between browsers as of yet. Please reply to my post if you experience any. Thanks!

至于兼容性,我还没有注意到浏览器之间的任何问题。如果您遇到任何问题,请回复我的帖子。谢谢!

#1


7  

A combination of Miquel Las Heras and Owen 'Coves' Jones's answers, who both submitted a not completely on-topic or not complete answer.

Miquel Las Heras和Owen'Coves'Jones答案的组合,他们都提交了一个不完全是主题或不完整的答案。

Use background trasitions (CSS3) and jQuery simultaneously.

同时使用后台trasition(CSS3)和jQuery。

JSFiddle

的jsfiddle

jQuery

jQuery的

$(document).ready(function () {
    $(window).scroll(function () {
        if ($(document).scrollTop() > 100) {
            $("header").addClass("scrolled");
        } else {
            $("header").removeClass("scrolled");
        }
    });
});

CSS

CSS

header {
    background-color:blue;
    -webkit-transition: background-color 700ms linear;
    -moz-transition: background-color 700ms linear;
    -o-transition: background-color 700ms linear;
    -ms-transition: background-color 700ms linear;
    transition: background-color 700ms linear;
}
header.scrolled {
    background-color: red;
}

Update February 3rd, 2017

browser support is very good, and the less performing jQuery solution below should not be used. Browser support.

浏览器支持非常好,不应该使用性能较差的jQuery解决方案。浏览器支持。

Cross-browser solution

If you want to make it more cross-browser compatible, you can try the color plugin. But from what I've tested, it has quite a bad performance. JSFiddle

如果您想使其更兼容跨浏览器,您可以尝试使用颜色插件。但是根据我的测试,它的性能相当糟糕。的jsfiddle

$(document).ready(function () {
    $(window).scroll(function () {
        if ($(document).scrollTop() > 100) {
            $("header").animate({
                backgroundColor: "red"
            }, 200);
        } else {
            $("header").animate({
                backgroundColor: "blue"
            }, 200);
        }
    });
});

Don't forget the plugin itself:

不要忘记插件本身:

//cdnjs.cloudflare.com/ajax/libs/jquery-color/2.1.2/jquery.color.js

#2


2  

I prefer to create 2 css classes for this type of issues. One for when window is scrolled and one for when it's not:

我更喜欢为这类问题创建2个css类。一个用于何时滚动窗口,一个用于何时不滚动:


    header { background: transparent; }
    header.scrolled { background: #f2f2f2; }

Then the javascript should be:

那么javascript应该是:


    $(function () {
      $(window).scroll(function () {
        if($(document).scrollTop()>100){
          $('header').addClass('scrolled');
        }
        else {
          $('header').removeClass('scrolled');
        }
      });
    })

#3


2  

First, as was mentioned in the other answer, you will need to include jQuery UI or the jQuery Color plugin for color animation.

首先,正如在另一个答案中提到的,您将需要包含jQuery UI或用于颜色动画的jQuery Color插件。

Second, and this is just winging it, but give this the old college try:

第二,这只是它的翼,但是给这个旧的大学尝试:

$(function(){
    $(window).scroll(function(){
        var $scrollPercent = ($(document).scrollTop() / 100);

        if($scrollPercent <= 1){
            $('header').css({backgroundColor:'rgba(0,0,0,'+$scrollPercent+')'});
        }
    });
});

This should give you a gradual fade in based on the amount down the page you scroll. This means that if you scroll 50 px down, your background color opacity would be set to 50% (50 px down / 100 px height wanted). You can also easily change the amount of height that you want to scroll down to reach full opacity very easily this way.

这应该会根据您滚动页面的数量逐渐淡出。这意味着如果向下滚动50像素,您的背景颜色不透明度将设置为50%(50 px向下/ 100 px高度需要)。您也可以通过这种方式轻松更改要向下滚动以达到完全不透明度的高度。

EDIT So it turns out you just want to fade in the color after 100px ... not my gradual fade in. No problem.

编辑所以事实证明你只想在100px之后淡出颜色...而不是逐渐淡入。没问题。

Others have pointed out the wonderful (and much better) CSS3 way to do it ... create a transition effect, and add a class on scroll. I won't steal their thunder, but I shall provide an alternative that works back to ancient browsers too.

其他人已经指出了这样做的奇妙(并且好得多)的CSS3方法......创建过渡效果,并在滚动上添加一个类。我不会偷他们的雷声,但我会提供一种可以回溯到古代浏览器的替代方案。

Add an additional line of HTML inside of your header at the top:

在顶部的标题内添加额外的HTML行:

<div class="header">
    <div class="headerBackground"></div>
    <!-- other header stuffs -->
</div>

Then set its CSS as such:

然后设置它的CSS:

.header {
    position:relative;
}

.headerBackground {
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    background-color:rgb(0,0,0);
    opacity:0;
    filter:alpha(opacity=0); // for IE8 and below
}

Then use the following jQuery:

然后使用以下jQuery:

$(function(){
    $(window).scroll(function(){
        var $bg = $('.headerBackground');

        if($(document).scrollTop() >= 100){
            $bg.animate({opacity:1},500); // or whatever speed you want
        } else {
            $bg.animate({opacity:0},500);
        }
    });
});

This also has the added benefit of not requiring another library (jQuery UI / jQuery Color plugin). The downside is, of course, the non-semantic HTML. Like I said, just another alternative.

这还有一个额外的好处,就是不需要另一个库(jQuery UI / jQuery Color插件)。当然,缺点是非语义HTML。就像我说的,只是另一种选择。

#4


0  

your code is correct, but jQuery does not natively support color animation. you need a plugin or jquery-ui for that: http://jqueryui.com/animate/

你的代码是正确的,但jQuery本身不支持颜色动画。你需要一个插件或jquery-ui:http://jqueryui.com/animate/

EDIT: actually, your code is kinda wrong. you want to set the backgroundColor to something. background: 1 is invalid css:

编辑:实际上,你的代码有点不对劲。你想将backgroundColor设置为某种东西。 background:1是无效的css:

so .css({'backgroundColor': 'red'}) and then .css({'backgroundColor': 'blue'})

所以.css({'backgroundColor':'red'})然后.css({'backgroundColor':'blue'})

#5


0  

If you don't need to support a lot of older browsers you can animate background colours with a combination of jQuery and css3 transitions:

如果您不需要支持许多旧版浏览器,可以使用jQuery和css3过渡组合为背景颜色设置动画:

Take the HTML:

拿HTML:

<div id="myBox">Stuff here</div>

And the javascript:

和javascript:

var myBox = $('#myBox');

myBox.on('click', function (el) {

    myBox.css('background-color', 'red');

}

Then click the element #myBox will change its background colour red. Instantly, with no fade.

然后单击元素#myBox将其背景颜色更改为红色。瞬间,没有褪色。

If you also put in place the css code:

如果您还放置了css代码:

#myBox {
    -webkit-transition: background-color 300ms ease-in-out;
    -moz-transition: background-color 300ms ease-in-out;
    transition: background-color 300ms ease-in-out;
}

Then any colour changes to the background will be faded over 300ms. Works on all latest version browsers, but not on IE 9 and below.

然后任何颜色变化到背景将褪色超过300毫秒。适用于所有最新版本的浏览器,但不适用于IE 9及更低版本。

#6


0  

The solution that I ended up using is as follows:

我最终使用的解决方案如下:

I created a section that I'm fading in and out based on the scroll position.

我创建了一个基于滚动位置淡入淡出的部分。

CSS

.backTex {
    width:100%;
    height:500px;
    margin-top:50px;
    background-color: @myGreen;
    //Height
    transition: height 0.5s ease;
    -webkit-transition: height 0.5s ease;
    -moz-transition: height 0.5s ease;
    -o-transition: height 0.5s ease;
    -ms-transition: height 0.5s ease;
    //Background-Color
    transition: background-color 0.5s ease;
    -webkit-transition: background-color 0.5s ease;
    -moz-transition: background-color 0.5s ease;
    -o-transition: background-color 0.5s ease;
    -ms-transition: background-color 0.5s ease;
    transition: background-color 0.5s ease;
} 

jQuery

$(document).scroll(function() {
        var positionScroll = $(this).scrollTop();

        if(positionScroll <= 499) {
            $(".backTex").css("background-color", "#fff");    
        } else if (positionScroll > 500 && positionScroll < 1100) {
            $(".backTex").css("background-color", "#2ecc71");
        } else {
            $(".backTex").css("background-color", "#fff");
        }
    });

As far as compatibility, I haven't noticed any issues between browsers as of yet. Please reply to my post if you experience any. Thanks!

至于兼容性,我还没有注意到浏览器之间的任何问题。如果您遇到任何问题,请回复我的帖子。谢谢!