How to rotate an image by a random amount using CSS?

你说的曾经没有我的故事 提交于 2019-12-01 02:47:06

问题


I have a gallery of 20 images on my web page that I would like to rotate by a random amount (-5 to 5 degrees) upon hover over each image. If possible, I'd like to use just CSS. If not, I would be open to using JavaScript or jQuery.

My CSS is as follows:

.photo:hover {
    z-index:1;
    transform:rotate(6deg) scale(1.25);
    -webkit-transform:rotate(6deg) scale(1.25);
    -moz-transform:rotate(6deg) scale(1.25);
    -ms-transform:rotate(6deg) scale(1.25);
}

6deg should be a random number, so every time the user hovers over an image, it rotates by a random amount between -5 and 5. Can I call a JavaScript function from within the CSS, or even a JavaScript variable? That would be better than creating 20 different CSS ids.

How can I accomplish this? Thanks!


回答1:


You won't need separate CSS IDs, but you could use some jQuery on the class. .each() is used instead of .css() directly here because otherwise the random angle would be generated once and used for all of the images. To rotate individally on hover:

$('.photo').hover(function() {
    var a = Math.random() * 10 - 5;
    $(this).css('transform', 'rotate(' + a + 'deg) scale(1.25)');
}, function() {
    $(this).css('transform', 'none');
});

If you want to smoothly animate these transformations, you can simply add a transform CSS property to the class:

.photo {
    transition: transform 0.25s linear;
}

Demonstration: http://jsbin.com/iqoreg/1/edit



来源:https://stackoverflow.com/questions/13504750/how-to-rotate-an-image-by-a-random-amount-using-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!