问题
I'm not sure how to use using jQuery, but has a CSS3 property: transform: rotate
it could be used along with jQuery?
transform:rotate;
-ms-transform:rotate;
-webkit-transform:rotate;
JSFIDDLE
回答1:
Try this fiddle:
http://jsfiddle.net/kDSqB/
It's not 100% accurate in working out full rotation, but I think that night be the fiddle environment.
The code here:
var $cog = $('#cog'),
$body = $(document.body),
bodyHeight = $body.height();
$(window).scroll(function () {
$cog.css({
'transform': 'rotate(' + ($body.scrollTop() / bodyHeight * 360) + 'deg)'
});
});
回答2:
Here's a simple jQuery example, check the modified JSFiddle:
http://jsfiddle.net/g3k6h/5/
CSS will handle rotations > 360 and < 0 for me so I didn't even bother doing that and adjust the rotation value based on the distance scrolled. I didn't worry about trying to account for a full rotation either so that it better flowed with the speed and distance scrolled. This solution depends on jQuery but could 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
});
});
})
回答3:
I started with OneOfOne's solution and added animations to it. Start the animation on the scroll
event, end it with the 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 rotation amount is based on the scroll position, where mine just keeps rotating while you are scrolling, which is how I understood the question.
回答4:
Something like this, jQuery should use the correct css3 prefix. http://jsfiddle.net/g3k6h/2/
$(function() {
$('.gear').click(function() {
$(this).css('transform', 'rotate(30deg)');
});
});
来源:https://stackoverflow.com/questions/18540474/how-to-rotate-image-when-scrolling-using-css-transform