javascript - JS (CSS) dynamic background image moving -
i made little script makes photo background scroll up/button in same time page scrolling. problem background image scrolling after page scrolling (it have delay).
question: how may make move background image page scrolling in example http://shapebootstrap.net/item/1524936-unika-responsive-one-page-html5-template/live-demo ?
i made plnkr code: https://plnkr.co/edit/e6ocuf4sxsa80pi6xanj?p=preview
var bgscroll = function(lastscrolltop, elem) { lastscrolltop = $(window).scrolltop(); $(elem).css('transition', 'all .5s'); $(elem).css('background-position', '0% ' + parseint(-lastscrolltop / 2) + 'px'); console.log('lastscrolltop = ' + lastscrolltop); }; $(window).load(function() { var lastst = 0; var homeelem = '#add-outer-container'; $(window).on("scroll", function() { bgscroll(lastst, homeelem); }); });
html, body { height: 100%; margin: 0; padding: 0; background-color: gray; } #add-outer-container { width: 100%; height: 500px; background: #fff url(http://www.gettyimages.pt/gi-resources/images/homepage/hero/pt/pt_hero_42_153645159.jpg) no-repeat fixed 0% 0%; overflow: hidden; color: white; border: 1px solid red; }
<!doctype html> <html lang="en"> <head> <!-- version 0.6.1.0 --> <title>test</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script src="app.js"></script> <link rel="stylesheet" type="text/css" href="app.css"></link> </head> <body> <div id="add-outer-container"></div> <div style="height: 1500px; color: green;"></div> </body> </html>
what looking called parallax effect. there several libraries can (http://pixelcog.github.io/parallax.js/ instance). simplest solution this:
// handle window scroll event $(window).scroll(function () { // store distance scrolled var scrolled = $(window).scrolltop() + 1; // set scroll speed var scrollspeed = 0.3; // update background position $("#add-outer-container").css('background-position', '0' + -(scrolled * scrollspeed) + 'px'); });
body { min-height:3000px; } #add-outer-container { background:url(http://www.gettyimages.pt/gi-resources/images/homepage/hero/pt/pt_hero_42_153645159.jpg) no-repeat fixed; width:100%; height:500px; margin:0 auto; border: 1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="add-outer-container"></div>
Comments
Post a Comment