How to rotate an image while scrolling using CSS transform?

I'm not sure how to use jQuery, but it has CSS3: transform: rotate property

can it be used with jQuery?

transform:rotate; -ms-transform:rotate; -webkit-transform:rotate; 

JSFIDDLE

+4
source share
4 answers

Try this script:

http://jsfiddle.net/kDSqB/

It is not 100% more accurate when developing a full rotation, but I think there will be a violin environment this night.

The code is here:

 var $cog = $('#cog'), $body = $(document.body), bodyHeight = $body.height(); $(window).scroll(function () { $cog.css({ 'transform': 'rotate(' + ($body.scrollTop() / bodyHeight * 360) + 'deg)' }); }); 
+12
source

Here is a simple jQuery example, check out the modified JSFiddle:

http://jsfiddle.net/g3k6h/5/

CSS will handle rotations> 360 and <0 for me, so I didn’t even bother to do this and adjust the rotation value based on scrolling by distance. I was not worried about trying to explain the full turn so that it would flow better with scrolling speed and distance. This solution depends on jQuery, but can easily be done without it.

 $(function() { var rotation = 0, scrollLoc = $(document).scrollTop(); $(window).scroll(function() { var newLoc = $(document).scrollTop(); var diff = scrollLoc - newLoc; rotation += diff, scrollLoc = newLoc; var rotationStr = "rotate(" + rotation + "deg)"; $(".gear").css({ "-webkit-transform": rotationStr, "-moz-transform": rotationStr, "transform": rotationStr }); }); }) 
+6
source

I started with OneOfOne solution and added animations to it. Run the animation in the scroll event, end it with mouseup . http://jsfiddle.net/g3k6h/4/

 var rotation = 0; var interval; var gear = $('.gear'); function animate() { gear.css('transform', 'rotate('+rotation+'deg)'); rotation += 10; rotation %= 360; } function startAnim() { if (!interval) { interval = setInterval(animate, 100); } } function stopAnim() { clearInterval(interval); interval = null; } $(document).scroll(startAnim).mouseup(stopAnim); 

Jamesgauld's answer is similar to mine, except that the amount of rotation is based on the scroll position, where mine just keeps spinning while scrolling, and that is how I understood the question.

+1
source

Something like this, jQuery should use the correct css3 prefix. http://jsfiddle.net/g3k6h/2/

 $(function() { $('.gear').click(function() { $(this).css('transform', 'rotate(30deg)'); }); }); 
-one
source

Source: https://habr.com/ru/post/1499863/


All Articles