首页 > 解决方案 > 我想通过单击按钮来移动图像?

问题描述

我想通过单击按钮来移动 img。我知道这个问题被问了很多,但我无法使用它们。

继承人相关的HTML:

<button class="ggE" (click)="gegenEnemy(chosenHero, actualEnemy);moveFist(); ...
  <div class="col">
    <img id="img" class="fist" src="...">

这是函数(打字稿):

moveFist(): void {
    document.getElementById('img').classList.add('fist');
  }

还有我的css,它使图片从左向右移动:

.fist {
  width: 70px;
  height: 70px;
  position: relative;
  animation-name: example;
  animation-duration: 2s;
}

@keyframes example {
  0%   {left:50px; top:20px;}
  100% {left:450px; top:20px;}
}

那么为什么我不能通过单击按钮来连接它呢?

标签: css

解决方案


首先验证您的HTML代码

<button class="ggE" onclick="moveFist();">button</button>
<div class="col">
  <img id="img" class="" src="https://via.placeholder.com/150">
<div>

编辑:

function moveFist(){
  
  document.getElementById("img").classList.remove("fist");
  
  // element.offsetWidth = element.offsetWidth;
  // Do this instead:
  
  void img.offsetWidth;
  
  document.getElementById("img").classList.add("fist");
}

通过它的偏移宽度设置img的宽度,即 img.offsetWidth;

你可以这样吗?

function moveFist(){
  
  document.getElementById("img").classList.remove("fist");
  
  // element.offsetWidth = element.offsetWidth;
  // Do this instead:
  
  void img.offsetWidth;
  
  document.getElementById("img").classList.add("fist");
}
img{
  width: 70px;
  height: 70px;
  position: relative;
  left:50px;
  animation-duration: 2s;
  top:20px;
}
.fist{
  position:relative;
  animation-name: example;
}

@keyframes example {
  0%   {left:50px; top:20px;}
  100% {left:450px; top:20px;}
}
<button class="ggE" onclick="moveFist()">button</button>
<div class="col">
  <img id="img" class="" src="https://via.placeholder.com/150">
<div>


推荐阅读