更改滚动标题的背景颜色

比利

我想在滚动时更改标题的背景颜色(从透明到黑色)。我怎样才能做到这一点?

我使用 CMS 来创建标题。这是我目前的代码:

<script>
  jQuery(function($) {
    $(window).scroll(function() {
      if ($(document).scrollTop() > 50) {
        $('#section-padding').addClass('reduce-section-padding');
        $('#row-width').addClass('increase-row-width');
        $('#my-site-logo').addClass('reduce-logo');
      } else {
        $('#section-padding').removeClass('reduce-section-padding');
        $('#section-padding').addClass('slow-transition');
        $('#row-width').removeClass('increase-row-width');
        $('#row-width').addClass('slow-transition');
        $('#my-site-logo').removeClass('reduce-logo');
        $('#my-site-logo').addClass('slow-transition');
      }
    });
  });
</script>

<style>
  .reduce-section-padding {
    transition: all 0.9s ease-out 0s;
    padding-top: 0px !important;
    padding-bottom: 0px !important;
  }
  
  .reduce-logo {
    transition: all 0.9s ease-out 0s;
    transform: scale(0.8) !important;
    /* Standard syntax */
    /*content: url(/wp-content/uploads/2020/05/favicon.png) !important;*/
  }
  
  .increase-row-width {
    transition: all 0.9s ease-out 0s;
    width: 70% !important;
  }
  
  .slow-transition {
    transition: all 0.9s ease-out 0s;
  }
  
  #main-content {
    margin-top: 5vw;
  }
</style>
奥马尔·希沙尼

您可以像这样使用纯 JavaScript:(JSFiddle:https ://jsfiddle.net/omartheman949/5jLngzkh/12/ )将以下script标签及其内容放在现有script标签下(或将以下script标签的内容放在现有script标签内):

<script>
  var prevScrollpos = window.pageYOffset;
  window.onscroll = function() {
    var currentScrollPos = window.pageYOffset;
    if (window.pageYOffset === 0) {
      document.getElementById("header").style.backgroundColor = "transparent";
      document.getElementById("header").style.color = "black";
    } else {
      document.getElementById("header").style.backgroundColor = "black";
      document.getElementById("header").style.color = "white";
    }
    prevScrollpos = currentScrollPos;
  }
</script>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章