javascript 如何使用 CSS 随机旋转图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13504750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:59:09  来源:igfitidea点击:

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

javascriptjquerycssrandomnumbers

提问by Jordan H

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.

我的网页上有一个包含 20 张图片的画廊,我想在将鼠标悬停在每张图片上时随机旋转它们(-5 到 5 度)。如果可能,我只想使用 CSS。如果没有,我愿意使用 JavaScript 或 jQuery。

My CSS is as follows:

我的 CSS 如下:

.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.

6deg 应该是一个随机数,所以每次用户将鼠标悬停在图像上时,它都会在 -5 到 5 之间随机旋转。我可以从 CSS 中调用 JavaScript 函数,甚至是 JavaScript 变量吗?这比创建 20 个不同的 CSS id 更好。

How can I accomplish this? Thanks!

我怎样才能做到这一点?谢谢!

回答by Delan Azabani

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:

您不需要单独的 CSS ID,但您可以在类上使用一些 jQuery。在这里.each()使用而不是.css()直接使用,因为否则随机角度将生成一次并用于所有图像。要在悬停时单独旋转:

$('.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 transformCSS property to the class:

如果你想平滑地为这些转换设置动画,你可以简单地transform向类添加一个CSS 属性:

.photo {
    transition: transform 0.25s linear;
}

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

演示:http: //jsbin.com/iqoreg/1/edit