悬停显示随机图像 [英] Show random image on hover

查看:95
本文介绍了悬停显示随机图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在悬停一些文本或div时显示随机图像的方法.

I am looking for a way to show a random image upon hovering some text or a div.

尝试了几种CSS方式,但是如果没有jQuery或Javascript,我认为这是不可能的,两者都很好.

Tried a few CSS ways but I don't think it's possible without jQuery or Javascript, either is fine.

我的想法(过于复杂)是使用随机脚本,例如

My (way overcomplicated) idea was using a random script such as

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

然后使用一些嵌套的if语句(我知道)在图像文件上添加或删除类,其中4/5(无论如何)将具有隐藏标签,而随机的类会将其删除.我什至无法弄清楚,我绝对认为这是解决此问题的麻烦方法.有谁有更好的主意吗?非常感谢!

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

例如

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" />

这篇关于悬停显示随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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