简体   繁体   English

悬停显示随机图像

[英]Show random image on hover

I am looking for a way to show a random image upon hovering some text or a div. 我正在寻找一种悬停一些文本或div时显示随机图像的方法。

Tried a few CSS ways but I don't think it's possible without jQuery or Javascript, either is fine. 尝试了几种CSS方式,但我认为没有jQuery或Javascript也不可能,两者都很好。

My (way overcomplicated) idea was using a random script such as 我的想法(过于复杂)是使用随机脚本,例如

Math.floor(Math.random() * 10);

then using a few nested if statements (I know) to add or remove classes on the images files which 4/5 (orwhatever) would have hidden tags and the random one would get it removed. 然后使用一些嵌套的if语句(我知道)在图像文件上添加或删除类,其中4/5(无论如何)将具有隐藏标签,而随机的类会将其删除。 I couldn't even figure that out and I definitely think its a messy way to solve this. 我什至无法弄清楚,我绝对认为这是解决此问题的一种麻烦方法。 Does anyone have a better idea? 有谁有更好的主意吗? Thanks so much! 非常感谢!

You could have the image urls in an array and pick one randomly when the user hovers over the text. 您可以将图像网址放在一个数组中,并在用户将鼠标悬停在文本上方时随机选择一个。

eg 例如

 var arr = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"]; function getRandomImage() { var index = Math.floor(Math.random() * arr.length); return arr[index]; } $("#div").hover( function() { var image = getRandomImage(); $("#img").attr("src", image); console.log(image); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="div">hover over me</div> <img id="img" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM