首页 > 解决方案 > 滚动时固定标题下的阴影

问题描述

我正在创建一个网站,我希望滚动时在我的固定标题下有阴影。这意味着当网站加载时,标题下方没有阴影,但是当我滚动页面时,阴影应该出现在标题下方。这是我的CSS代码

编辑:我正在使用 reactjs 来呈现标题

.nav-heading {
  background-color: $white;
  top: 0;
  display: flex;
  flex-direction: row;
  position: fixed;
  width: 100%;
  z-index: 1;
  // margin-top: 1.25rem;
}
.nav-heading::after {
  position: fixed;
  box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.7);
}

标签: htmlcssreactjs

解决方案


您可以使用 JQuery,这是一个 javascript 库。

首先,您需要安装 JQuery。一种简单的方法是通过 CDN。

<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>

然后像这样添加你的脚本。

<script>
  $(window).scroll(function(){
    $(".nav-heading").css("box-shadow","here insert the value you want for the box-shadow")
  })
</script>

如果要在滚动后使阴影淡出,可以使用:

<script>
  $(window).scroll(function(){
    $(".nav-heading").css("box-shadow","here insert the value you want for the box-shadow").fadeOut( "slow" );
  })
</script>

您可以访问更多关于: https ://code.jquery.com/

编辑:如何使用 React.js

您可以创建函数来处理滚动或不滚动的状态。

   constructor() {
     super();
     this.state = {
        className: 'notShadow'
     }
   }

   handleScroll() { 
    if (document.documentElement.scrollTop > 430) {
       this.setState({
         className: 'withShadow'
       })
     } 
   }
 
   componentDidMount() {
     window.onscroll = () => this.handleScroll()
   }

然后在您的标题中,您可以将状态称为类。

<Nav className={this.state.className} />

如果您不知道可以使用的像素数:

console.log(document.documentElement.scrollTop);

推荐阅读