首页 > 解决方案 > 为什么可折叠标题不会在动态滚动时折叠?

问题描述

我网站上的可折叠标题似乎不起作用,我想知道这是否是我设置 HTML 的方式?我试图让标题在滚动时从 125px 折叠到 75px,但我似乎无法让它工作。我已经看到我在其他网站上使用的 JavaScript,所以我并不完全清楚这个网站发生了什么。有人看到我的代码有任何问题吗?似乎它对我来说应该可以正常工作。非常感谢!

<header id="masthead" class="site-header">

    <section class="header-top" id="header-top">
    
        <div class="container content">

            <div class="top-search">
            <?php get_search_form( ); ?>
            </div>

            <div class="site-branding">
                <a  href="<?php echo site_url( );?>"><img class="logo" src="<?php echo get_template_directory_uri(  ) . '/logo.svg'?>"></a>                 
            </div>  

            <div class="header-right">

                <p class="contribute"><a href="#">Contribute</a></p>   
                
            </div>  

        </div>

    <div class="container">

            <div class="top-search">
            
            </div>

            <div class="site-branding">             
            </div>  

            <div class="header-right">                  
                
            </div>              

        </div>
        

        <div class="container header-top-block" id="titles" style="display:block">              

                <h3 class="header-block-heading-line" id="soup">
                
                    <a href="<?php echo home_url(); ?>" target="">
                    Hello
                    </a>
                
                </h3>

        </div>

            </div>

          </div>
      </div>
    </section> <!-- end header main -->

    <section class="header-nav">
        <div class="container borders">
            
        </div>  
        
    </section>

</header><!-- #masthead -->

.header-top {
width: 100%;
z-index: 2;
position: relative;
background: $white;
position:fixed;
min-height: 125px;
&.collapsed {
    min-height: 50px;
}

.container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}

window.onscroll = function() {myFunction()};

function myFunction() {
  if (document.documentElement.scrollTop > 100) {
   if(!document.getElementById("header-top").classList.contains('collapsed')){
       document.documentElement.scrollTop += 100;
       document.getElementById("header-top").className = "header-top collapsed";
     }


} else {
 if(document.getElementById("header-top").classList.contains('collapsed')){
   document.getElementById("header-top").className = "header-top";
   document.documentElement.scrollTop = 0;


    }
   }
 }

标签: javascript

解决方案


好像你忘了}&.collapsed声明后添加。此外,如果您使用的是纯 CSS,则此代码将不起作用(您使用的是 SCSS 语法)


推荐阅读