【问题标题】:jQuery add and removeClass background with transitionjQuery添加和removeClass背景与过渡
【发布时间】:2018-02-01 09:54:51
【问题描述】:

我目前正在设置我的标题,添加一个将背景更改为渐变的类。

这是我使用 jQuery 添加和删除类的代码。

$(document).ready(function(){
    $(window).scroll(function(){
        if($(this).scrollTop() > 100){
            $('header').addClass('gradientHeader');         
        }else{
            $('header').removeClass('gradientHeader');
        }
    });    
});

对于 CSS

.gradientHeader{
    background: linear-gradient(-45deg, #57cfb0, #2ab5d3);
    transition: background 0.3s;
}

我的添加和删除类正在工作,但背景转换没有触发..

使用带有 jquery 的 .css 会触发转换,但它是使用 background-color 并且我想要使用 background: linear-gradient(-45deg, #57cfb0, #2ab5d3); 的特定颜色

$('gradientHeader').css("background-color", "red");

这样做的解决方法是什么?

【问题讨论】:

  • 锚链接上的线性渐变很好,我想做的是在滚动事件后更改背景,问题是使用 jquery 的线性渐变转换没有触发,它只是捕捉到线性没有过渡.. T_T
  • 问题与其他线程相同 - 浏览器无法使用 linear-gradient 进行转换,就像使用背景颜色一样。在这种情况下,问题与 jQuery 无关。您可以在此处应用该线程中的解决方案。如果您遇到问题,我会在下面创建一个答案。
  • 嗯,这似乎令人困惑,并会在它上面.. T_T 谢谢..

标签: jquery html css


【解决方案1】:

根据我上面的 cmets,这里有一个答案,可以帮助您了解一种执行此操作的方法。

使用::before 伪类,我在我们的div 后面添加了线性渐变背景。当我说后面时,我的意思是它实际上在 div 的内容和正常背景颜色之下,因为它有z-index: -1

然后该按钮将切换该 div 上的 .gradient 类,这只会使正常的背景颜色透明,从而显示下面的渐变。浏览器支持颜色和transparent 之间的转换。

$('button').click(function() {
  $('div').toggleClass('gradient');
});
div {
  background-color: teal;
  transition: background-color .5s;
  width: 200px;
  height: 200px;
  position: relative;
}

div::before {
  background: linear-gradient(-45deg, #57cfb0, #2ab5d3);
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: -1;
}

div.gradient {
  background-color: transparent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <button>Toggle Gradient</button>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 2013-02-22
    • 1970-01-01
    相关资源
    最近更新 更多