如何使用CSS旋转图像随机数量? [英] How to rotate an image by a random amount using CSS?

查看:245
本文介绍了如何使用CSS旋转图像随机数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页上有一个20张图片,我想旋转一个随机数量(-5到5度)悬停在每个图像上。如果可能,我想只使用CSS。如果没有,我会开放使用JavaScript或jQuery。

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.

我的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应该是随机数字,因此每次用户将鼠标悬停在图片上,它旋转一个在-5和5之间的随机数。我可以从CSS中调用JavaScript函数,甚至是一个JavaScript变量?这将比创建20个不同的CSS ids更好。

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!

推荐答案

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

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');
});

如果要平滑地对这些转换进行动画处理,可以简单地添加 类属性的CSS属性:

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;
}

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

这篇关于如何使用CSS旋转图像随机数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆