如何在向下滚动页面时更改H1颜色

How can I change H1 color as you scroll down the page?

本文关键字:H1 颜色 滚动      更新时间:2023-09-26

我有一个页面,顶部有一张100%宽的大照片,照片顶部有一个标题。当你滚动经过照片时,我想让固定位置的标题改变颜色。我已经能够在jsfiddle中创建一个工作版本:

http://jsfiddle.net/dtZDZ/647/

这是javascript(我是JS新手)

    var tStart = 100 // Start transition 100px from top
,
tEnd = 300 // End at 300px
,
cStart = [255, 255, 255] // white
,
cEnd = [156, 156, 156] // black
,
cDiff = [cEnd[0] - cStart[0], cEnd[1] - cStart[1], cEnd[1] - cStart[0]];
$(document).ready(function () {
$(document).scroll(function () {
    var p = ($(this).scrollTop() - tStart) / (tEnd - tStart); // % of transition
    p = Math.min(1, Math.max(0, p)); // Clamp to [0, 1]
    var cBg = [Math.round(cStart[0] + cDiff[0] * p), Math.round(cStart[1] + cDiff[1] * p), Math.round(cStart[2] + cDiff[2] * p)];
    $("h1 a").css('color', 'rgb(' + cBg.join(',') + ')');
  });
});

不幸的是,一旦我开始滚动h1,当我将鼠标悬停在它上面时,它的颜色就不再改变了。此外,当我试图打开一个铬内有此代码的页面时,文本只是从白色变为黑色,而不是我指定的深灰色。有人知道如何解决这两个问题吗?

感谢

我不会显式设置颜色,而是使用类切换:

var title = $('h1:first'),
  titleText = title.find('a'),
  titleTextHeight = titleText.height(),
  meow = $('#meowmeow'),
  meowBottom = meow.offset().top + meow.outerHeight();
$(document).ready(function () {
    $(document).scroll(function () {
        if ($(document).scrollTop() + titleTextHeight > meowBottom) {
          titleText.addClass('bare');
        } else {
          titleText.removeClass('bare');
        }
    });
});

那么这只是选择器的问题:

h1 a {
    position:fixed;
    color: white;
    text-decoration:none;
    padding: 5%;
    font-size: 2em;
}
h1 a.bare {
    color: rgb(156, 156, 156);
}
h1 a:hover, h1 a.bare:hover {
    color: rgb(200, 200, 200)
}

http://jsfiddle.net/9PJ9g/1/

只要悬停不起作用,您正在设置的内联样式就会覆盖CSS中的:悬停状态。

快速修复:

h1 a:hover {
    color: rgb(200, 200, 200)!important;
}

此外,该链接在jsFiddle中设计不起作用,因为它在iframe中运行。如果出于某种原因您真的很想这样做,那么将target="_parent"添加到锚标记