简体   繁体   中英

Rotate element 180 degrees on scrolling

I'm looking to rotate an image 180 degrees when the user scrolls down on a web page. The rotation should happen during the time the image is visible in the viewport and the image should rotate back to its original positon when the user scrolls back up.

I got it working for the most part, but sometimes the rotation stops at seemingly random value below 180 degrees. I can't figure out why and want to make sure the image always rotates to 180.

 var iconRotate = $('.icon-rotate img'); if (iconRotate.length != 0) { $(window).scroll(function () { var page = window.pageYOffset, inner = window.innerHeight, result = (180 * page / (inner/3)); if (result < 180) { console.log(result); iconRotate.css({transform: 'rotate(-' + result + 'deg)'}); } }); } 
 .icon-rotate { width:300px; } img { width: 100%; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="icon-rotate"> <img src="http://68.media.tumblr.com/6324fd64b78c316379713480b8e44d29/tumblr_nd1rffWqEa1ryzl2ko1_1280.jpg" /> </div> 

You should really do a percentage based on scroll and the most you can scroll.

 var iconRotate = $('.icon-rotate img'); if (iconRotate.length != 0) { $(window).scroll(function () { var scroll = $(window).scrollTop(), maxScroll = $(document).height()-$(window).height(); iconRotate.css({transform: 'rotate(-' + (180 * scroll/maxScroll) + 'deg)'}); }); } 
 .icon-rotate { width:300px; } img { width: 100%; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="icon-rotate"> <img src="http://68.media.tumblr.com/6324fd64b78c316379713480b8e44d29/tumblr_nd1rffWqEa1ryzl2ko1_1280.jpg" /> </div> 

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