javascript jquery 背景颜色在滚动时淡入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19430241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:34:13  来源:igfitidea点击:

jquery background color fade in on scroll

javascriptjqueryhtmlcss

提问by mannygtr

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();
    });
})

回答by Bram Vanroy

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.

同时使用背景过渡 (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

2017 年 2 月 3 日更新

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

回答by Miquel Las Heras

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');
        }
      });
    })

回答by PlantTheIdea

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 像素/需要 100 像素高度)。您还可以通过这种方式轻松更改要向下滚动以非常轻松地达到完全不透明度的高度。

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

编辑所以事实证明你只是想在 100 像素后淡入颜色......不是我的逐渐淡入。没问题。

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。就像我说的,只是另一种选择。

回答by Stefan

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 设置为某些东西。背景:1 是无效的 css:

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

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

回答by Owen C. Jones

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 及更低版本。

回答by AnneXin

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

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

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!

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