繁体   English   中英

使用 JavaScript/jQuery 更改线性渐变百分比

[英]Use JavaScript/jQuery to change linear gradient percentage

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

这是 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即可实现。 只需使用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> 

删除结束引号前的分号。

$("#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%)")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM