简体   繁体   中英

Use JavaScript/jQuery to change linear gradient percentage

I have a page with a linear gradient in the wrapper element.

Here is the HTML:

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

The CSS is:

#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;
}

The gradient shows up ok on its own. However, I want to use js/jquery to change the gradient as I scroll down the page. I don't think the current js code is affecting anything at the moment. How do I fix this? Thanks.

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

It can be achieved without Javascript/jQuery. Simply by using CSS. Below is the example.

 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> 

Delete the semicolon before the closing quote.

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

It should look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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