【问题标题】:Add random image on hover using jquery使用jquery在悬停时添加随机图像
【发布时间】:2023-03-24 22:28:01
【问题描述】:

HTML和CSS很难修改,除了给div加上cla​​ss和ID。那么为什么我要尝试使用 JS Jquery 来处理它。

当我将鼠标悬停在 div 中的图像上时,我想随机显示 GIF。

当鼠标移出时,效果应该消失,以便可以再次看到原始图像。

(在本例中,目标是让 gif 随机出现。)

这是我一直在处理的代码。

const ImgLinks = [
"https://media.giphy.com/media/tJ1jipvvMs4r7xuZnI/giphy.gif",
"https://media.giphy.com/media/XFpIo4jKuUrjQHYHeq/giphy.gif",
"https://media.giphy.com/media/uxunn6z4qKrGsND3II/giphy.gif",
"https://media.giphy.com/media/XxRl7rbKSFvXEFoNzv/giphy.gif"
]; //sources are examples.
    
function getRandHoverGif() {
  const index = Math.floor(Math.random() * ImgLinks.length);
  return ImgLinks[index];
}

$("#hover-ani").hover(
  function() {

我不知道如何完成悬停功能。

【问题讨论】:

  • 把它分解成更小的步骤。从足够的 html 开始,以便在悬停时显示静态版本。然后一旦工作添加随机功能。目前您没有显示任何 html,因此如果有人想帮助您,他们必须从头开始编写所有内容。 minimal reproducible example 不是这样工作的

标签: jquery random hover jquery-hover


【解决方案1】:

悬停时设置图像src,悬停时删除src。在图像上应用一些 CSS 以获得期望的输出。

例子:

const ImgLinks = [
  "https://media.giphy.com/media/tJ1jipvvMs4r7xuZnI/giphy.gif",
  "https://media.giphy.com/media/XFpIo4jKuUrjQHYHeq/giphy.gif",
  "https://media.giphy.com/media/uxunn6z4qKrGsND3II/giphy.gif",
  "https://media.giphy.com/media/XxRl7rbKSFvXEFoNzv/giphy.gif"
]; //sources are examples.

function getRandHoverGif() {
  const index = Math.floor(Math.random() * ImgLinks.length);
  return ImgLinks[index];
}

$("#hover-ani").hover(
  function() {
    $("#img2").attr("src", getRandHoverGif());
  },
  function() {
    $("#img2").attr("src", "");
  }
);
#img1 {
  background-color: transparent;
  background-image: url("https://i.stack.imgur.com/XZ4V5.jpg");
  background-repeat: no-repeat;
  width: 600px;
  height: 400px;
  position: absolute;
  z-index: 1;
}

#img2 {
  position: absolute;
  top: 25px;
  left: 25px;
  z-index: 2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="hover-ani">
  <img id="img1"></img>
  <img id="img2"></img>
</div>

注意:您可以根据您的要求(gif 位置)编辑(自定义)您的 CSS。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    相关资源
    最近更新 更多