【问题标题】:Change background of fixed header when scrolling past elements滚动过去元素时更改固定标题的背景
【发布时间】:2014-03-12 12:08:12
【问题描述】:

我正在尝试在滚动页面上的某些 DIV 部分时更改固定标题的背景颜色,类似于:

http://www.adamrudzki.com/

我使用的部分没有固定高度。

我发现了类似的问题Change background-color while scrolling

(使用这个小提琴http://jsfiddle.net/cEvJk/18/

var t = $('#about').offset().top - 100;

$(document).scroll(function(){
    if($(this).scrollTop() > t)
    {   
        $('header').css({"background-color":"green"});
    } 
});

但我无法获得所有部分都重复的效果。

【问题讨论】:

  • header <header> 标签还是一个类?
  • example你给的表头其实是有透明背景的。
  • 你能展示你的小提琴或任何你目前正在工作的演示链接吗?
  • 嗨 Dhiraj Shah,我已经上传了一个网站示例到 jiraff.co.uk/demo/demo.html

标签: javascript jquery css background-color


【解决方案1】:

试试这个:

var t = $('#about').offset().top - 100;
var t1 = $('#work').offset().top - 100;

$(document).scroll(function(){
    if($(this).scrollTop() > t1) {   
        $('header').css({"background-color":"blue"});
    } else if($(this).scrollTop() > t) {   
        $('header').css({"background-color":"green"});
    } else {
        $('header').css({"background-color":"#520833"});
    }
});

var t2 = ... 以此类推。

不要忘记在 if 的顶部放置更高的值

【讨论】:

  • 这非常有效。非常感谢 Nathan P 的帮助!
  • 很高兴为您提供帮助:)
  • 我注意到,如果调整窗口大小,我设置它的方式会使它的执行方式略有不同 - 你知道是否有什么办法可以让这个脚本在浏览器调整大小时刷新?
  • @DaleIrwin 见here
【解决方案2】:

您可以像这样使用jQuery's .each() method 来简化一些事情:

Working Example

$(window).scroll(function () {
    $('.sect').each(function () {
        var w = $(window).scrollTop();
        var t = $(this).offset().top - 100;
        if (w > t) {
            $('header').css({
                "background-color": $(this).css('background-color')
            });
        }
    });
});

来自documentation

.each() 方法旨在使 DOM 循环结构简洁 并且不易出错。当被调用时,它会遍历 DOM 元素 它们是 jQuery 对象的一部分。每次回调运行时,它是 通过当前循环迭代,从 0 开始。更重要的是, 回调在当前 DOM 元素的上下文中触发,所以 关键字 this 指代元素。

【讨论】:

  • 这是做人的方法。您为什么要像以前的答案一样对值进行硬编码。试想一下,如果你有更多的部分,或者当你添加新的部分时,你想回到你的脚本并添加更多的 js 吗?这是安全的:)
【解决方案3】:

好的,所以我想出了THIS FIDDLE

$(document).scroll(function () {
    var x = $(this).scrollTop(),
        home = $('#home'),
        about = $('#about'),
        work = $('#work'),
        contact = $('#contact');

    if (x >= home.offset().top && x < (home.offset().top + home.height())) {
        $('header').css("background-color", "red");
    }
    if (x >= about.offset().top && x < (about.offset().top + about.height())) {
        $('header').css("background-color", "green");
    }
    if (x >= work.offset().top && x < (work.offset().top + work.height())) {

        $('header').css("background-color", "blue");
    }
    if (x >= contact.offset().top && x < (contact.offset().top + contact.height())) {
        $('header').css("background-color", "orange");
    }
});

【讨论】:

    猜你喜欢
    • 2018-12-28
    • 1970-01-01
    • 2013-04-23
    • 2021-04-15
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    相关资源
    最近更新 更多