如何仅在javascript中的onclick上播放gif

时间:2018-11-12 06:18:11

标签: javascript html css

我下面有一个代码,可从数组字符加载 gif动画,并将其加载到{{1} }。

image src 仅当我单击显示的gif时 I want to play the gif animation

它现在在加载gif后立即播放gif

.

How to change my code to display the gif from array as it is doing now but play the gif only when i click on it?
number = 0;
var animations = ['https://image.ibb.co/epha5A/giphy.gif',
  'https://image.ibb.co/epha5A/giphy.gif',
  'https://image.ibb.co/epha5A/giphy.gif'
];

function character() {

  image = document.getElementById('hiddenimageid');
  image.src = animations[number];

  console.log(number);
  number++;


}
.board {
  position: absolute;
  top: 4.3vh;
  left: 10vw;
  cursor: pointer;
}

.board img {
  width: 35.3vw;
  height: 45.5vh;
  border-radius: 15%;
}

2 个答案:

答案 0 :(得分:3)

我使用以下站点将gif转换为pnghttps://image.online-convert.com/convert-to-png

然后将onclick设置为img,以将src更改为您的gif

现在您可以对其他gif

进行此操作

number = 0;
var animations = ['https://image.ibb.co/epha5A/giphy.gif',
  'https://image.ibb.co/epha5A/giphy.gif',
  'https://image.ibb.co/epha5A/giphy.gif'
];


function character() {

  image = document.getElementById('hiddenimageid');
  image.src = animations[number];

}
.board {
  position: absolute;
  top: 4.3vh;
  left: 10vw;
  cursor: pointer;
}

.board img {
  width: 35.3vw;
  height: 45.5vh;
  border-radius: 15%;
}
<body>
  <div class="board">
    <img src=" https://i.stack.imgur.com/pqbOp.png" id="hiddenimageid" onclick="character();"/>
  </div>
</body>

答案 1 :(得分:3)

您在这里:

number = 0;
var animations = ['https://image.ibb.co/epha5A/giphy.gif',
  'https://image.ibb.co/epha5A/giphy.gif',
  'https://image.ibb.co/epha5A/giphy.gif'
];


 var refreshIntervalId = setInterval(function() {
  image = document.getElementById('hiddenimageid');
  image.src = animations[number];
},1)


function character() {
clearInterval(refreshIntervalId);
  image = document.getElementById('hiddenimageid');
  image.src = animations[number];

  console.log(number);
  number++;


}
.board {
  position: absolute;
  top: 4.3vh;
  left: 10vw;
  cursor: pointer;
}

.board img {
  width: 35.3vw;
  height: 45.5vh;
  border-radius: 15%;
}
<body onclick="character();">

  <div class="board">
    <img src="" id="hiddenimageid" />
  </div>
</body>

使用此解决方案,您无需将图像转换为png或jpeg。您可以直接使用您的代码。希望对您有帮助