【问题标题】:Use JavaScript/jQuery to change linear gradient percentage使用 JavaScript/jQuery 改变线性渐变百分比
【发布时间】:2019-08-11 08:43:12
【问题描述】:

我在包装元素中有一个带有线性渐变的页面。

这是 HTML:

<body>
    <div id="wrapper">
        <div></div>
        <div></div>
        <div></div>
    </div>
</body>

CSS 是:

#wrapper {
    position: relative;
    top: 0;
    bottom: 0;
    width: 100%;
    z-index: -1;
    background: -webkit-linear-gradient(rgba(0, 0,0,1) 0%, rgba(30,30,30,1) 60%, rgba(180,180,180,1) 100%); /* Safari 5.1 - 6.0 */
    background: -o-linear-gradient(rgba(0, 0,0,1) 0%, rgba(30,30,30,1) 60%, rgba(180,180,180,1) 100%); /* Opera 11.1 - 12.0 */
    background: -moz-linear-gradient(rgba(0, 0,0,1) 0%, rgba(30,30,30,1) 60%, rgba(180,180,180,1) 100%); /* Firefox 3.6 - 15 */
    background: linear-gradient(rgba(0, 0,0,1) 0%, rgba(30,30,30,1) 60%, rgba(180,180,180,1) 100%);
    padding-bottom: 1px;
}

渐变本身就可以显示。但是,我想在向下滚动页面时使用 js/jquery 来更改渐变。我认为当前的 js 代码目前没有任何影响。我该如何解决?谢谢。

$(window).scroll(function(){
        var topDis = $(window).scrollTop();
        $("#wrapper").css("background", "linear-gradient(rgba(0, 0, 0, 1) 0%, rgba(30,30,30,1) " + (60 - topDis/100) + "%, rgba(180,180,180,1) 100%);");
        $("#wrapper").css("background", "-webkit-linear-gradient(rgba(0, 0, 0, 1) 0%, rgba(30,30,30,1) " + (60 - topDis/100) + "%, rgba(180,180,180,1) 100%);")
      });

【问题讨论】:

    标签: javascript jquery html css gradient


    【解决方案1】:

    删除右引号前的分号。

    $("#wrapper").css("background", "-webkit-linear-gradient(rgba(0, 0, 0, 1) 0%, rgba(30,30,30,1) " + (60 - topDis/100) + "%, rgba(180,180,180,1) 100%);")
    

    应该是这样的:

    $("#wrapper").css("background", "linear-gradient(rgba(0, 0, 0, 1) 0%, rgba(30,30,30,1) " + (60 - topDis/100) + "%, rgba(180,180,180,1) 100%)")
    

    【讨论】:

      【解决方案2】:

      无需 Javascript/jQuery 即可实现。只需使用 CSS。下面是例子。

      body {
        height: 3000px;  /* height has to be defined for scrolling */
        background: linear-gradient(141deg, #0fb8ad 0%, #1fc8db 51%, #2cb5e8 75%);
        }
      <h1>Change Background Gradient on Scroll</h1>
      
      <h2>Linear Gradient - Top to Bottom</h2>
      <p>This linear gradient starts at the top. It starts green, transitioning to blue.</p>
      
      <h2 style="position:fixed;">Scroll to see the effect.</h2>

      【讨论】:

      • 感谢您的回答,但我认为这与我想要达到的效果不同。首先,我的文档高度不能固定,因为它是不同页面的模板。其次,我希望渐变的中间停止点根据滚动而变化,而不是静态的。
      猜你喜欢
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      • 2021-12-18
      • 2021-03-24
      相关资源
      最近更新 更多