【问题标题】:how to fix sticky header on scroll?如何修复滚动上的粘性标题?
【发布时间】:2021-08-31 06:04:27
【问题描述】:

您好,当我从上到下滚动时,我正试图将标题粘贴在屏幕上。这个 js 函数应该(按照 yt 教程)粘贴我的标题来更改我的导航颜色,但它不起作用。

<script type="text/javascript">
    window.addEventListener('scroll', function(){
        var header = document.querySelector('header');
        header.classList.toggle('sticky', window.scrollY > 0);
    });
</script>

这是我的 CSS

header{
 position: fixed; /*fijamos el header a la pantalla*/
 top:0; /*ayudamos a que el header quede fijo*/
 left:0; /*ayudamos a que el header quede fijo*/
 width: 100%; /*ancho del header*/
 padding: 2.500em 6.250em; /*40px arriba abajo y 100px a los lados*/
 z-index: 100; /*orden de elemento posicionado*/
 display: flex; /*caja flexible*/
 justify-content: space-between; /*separamos los elementos de la caja*/
 align-items:center; /*centramos los elementos*/
 transition: 0.5s;
}
header .sticky{
 background: #fff;
 padding: 20px 100px;
 box-shadow: 0 5px 20px rgba(0,0,0,0.1);
}
header .logo{
 color: #fff;
 font-size: 1.5em; /*24px*/
 text-transform: uppercase;
 text-decoration: none;
 font-weight: 700;
 letter-spacing: 0.125em; /*2px - espacio entre letras*/ 
}
header .sticky .logo{
 color: #111;
}
header ul{
 position: relative;
 display:flex;
}
header ul li{
 position:relative;
 list-style: none;
}
header ul li a{
 position: relative;
 display: inline-block;
 margin: 0 0.938em; /*0 arriba abajo y 15px a los lados*/
 color: #fff; /*color texto*/
 text-decoration: none; /*quitamos subrayado*/
}
header .sticky ul li a{
 color: #111;
}

最初我的标题是黑色的,带有白色文本,所以当我从上到下滚动时,它应该坚持将我的白色文本更改为黑色,这样当我在白色背景的部分中导航时我可以欣赏它...

查看 js 功能的 html 开发工具,当我滚动时它会被调用 image 但什么都没有发生,它甚至没有改变文本颜色/背景

我的 HTML

https://pastebin.com/pM1EEU50

【问题讨论】:

标签: javascript html css


【解决方案1】:

请注意element .classelement.class 是不同的。 当您在函数中定位 header 元素时,我可以假设您的问题是您正在寻找一个具有 .sticky 类的元素,当您选择 header .sticky 时,它是 header 的后代;但你需要标题本身。

header .sticky {
  background: #fff;
  padding: 20px 100px;
  box-shadow: 0 5px 20px rgba(0,0,0,0.1);
}

考虑使用header.sticky 选择具有.sticky 类的标头。您还必须修复其他选择器。

header.sticky {
  background: #fff;
  padding: 20px 100px;
  box-shadow: 0 5px 20px rgba(0,0,0,0.1);
}

查看CSS Selectors 了解更多选择器模式。

【讨论】:

    猜你喜欢
    • 2020-08-31
    • 2016-04-30
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 2018-09-24
    • 2020-10-15
    • 2019-07-27
    相关资源
    最近更新 更多