使用Javascript和PHP在不同的页面上以不同的方式设置标题动画

Header animated differently on separate pages using Javascript and PHP

本文关键字:方式 设置 标题 动画 Javascript 使用 PHP      更新时间:2023-09-26

我有一个header.php文件,它被调用到我的所有页面中,其中有:

<header <?php if (is_page('Home')) { echo 'id="home-masthead" class="site-header" role="banner"'; } else { echo 'id="masthead" class="site-header" role="banner"'; } ?>>

这意味着,如果我在主页上,我可以在CSS中使用#home-masthead为该页面的页眉设置样式,而要为所有其他页面设置样式,我可以仅使用#masthead为页眉设置样式。

我的问题是,即使php为我的主页提供标题id="#home-masthead" and all other pages id="mashead"`,并且样式在这些页面上也有效。当我试图在任何页面上动画化标题id,但主页不起作用。

这是我的CSS:

#masthead {
  height: 100px;
  transition: all 0.5s;
  /* other styles here */
}
.animate#masthead {
  height: 75px;
}

和我的JS:

// Header Shrink
$(function() {
  var shrinkHeader = 125;
  $(window).scroll(function() {
    var scroll = getCurrentScroll();
    if ( scroll >= shrinkHeader ) {
      $('#home-masthead, #masthead, #logo, #list-container').addClass('animate'); // header-animate
    }
    else {
      $('#home-masthead, #masthead, #logo, #list-container').removeClass('animate'); // header-animate
    }
  });
  function getCurrentScroll() {
    return window.pageYOffset || document.documentElement.scrollTop;
  }
});

tl;drJS头动画只在主页上工作,而不能在其他页面上工作,这可能是因为php代码更改了主页以外页面的id。

试试这个代码。console.log应该出现在开发工具的控制台选项卡上

if ( scroll >= shrinkHeader ) {
  console.log("entered if");
  $('#home-masthead, #masthead, #logo, #list-container').addClass('animate'); // header-animate
}
else {
  console.log("entered else");
  $('#home-masthead, #masthead, #logo, #list-container').removeClass('animate'); // header-animate
}