CSS 移动元素时过渡不起作用

CSS transition not working when moving element

我有一个 CSS element/ball,点击后我将移动到新坐标。

这有效,但是我正在应用的转换似乎没有生效。

小球跳到新位置。我想让它慢慢animate/transition/move到新坐标

我做错了什么?

.ball {
    width: 30px;
    height: 30px;
    border-radius: 50%; 
    background-color: #FF5722;
    position: absolute;
    // d.style.transition = "all 1s ease-in";
    transition: all 3s ease-in-out;
    // -webkit-transition: all 1s ease-in-out;
    // -moz-transition: all 1s ease-in-out;
    // -o-transition: all 1s ease-in-out;
    // -ms-transition: all 1s ease-in-out;
  }

 handleClick = (e) => {
      console.log('ball clicked');
      var d = document.getElementById('ball');
      console.log('d', d);
      d.style.x =  12 + "px";
      d.style.top = 341 + "px";
      d.style.transition = "all 1s ease-in";
  }

谢谢

您必须为 xtop 分配默认值,否则您将尝试从无到有进行转换。

P.S。您的 CSS 似乎正在选择具有 CLASS ball 的元素,而不是 ID 为 ball 的元素。在 CSS 中使用 #ball 而不是 .ball。 (归功于 jaromanda-x)

window.onclick = (e) => {
      console.log('ball clicked');
      var d = document.getElementById('ball');
      console.log('d', d);
      d.style.x =  12 + "px";
      d.style.top = 341 + "px";
      d.style.transition = "all 1s ease-in";
  }
#ball {
    width: 30px;
    height: 30px;
    border-radius: 50%; 
    background-color: #FF5722;
    position: absolute;
    // d.style.transition = "all 1s ease-in";
    transition: all 3s ease-in-out;
    // -webkit-transition: all 1s ease-in-out;
    // -moz-transition: all 1s ease-in-out;
    // -o-transition: all 1s ease-in-out;
    // -ms-transition: all 1s ease-in-out;
    x:0; /* default value */
  top:0; /* default value */
  }
<div id="ball">

好像有几点需要更正;

  • 球的样式由 CSS 中的 .ball class 设置,其中球元素是通过 id 访问的,这表明存在潜在问题。 ball class 是否应用于 ID 为 ball 的元素?
  • 样式对象上的 x 属性 应替换为 left 属性 以确保球元素的水平移动
  • 确保在修改任何 CSS 属性之前将转换分配给目标元素

这是一个演示这些更正的示例:

const handleClick = (e) => {

  console.log('ball clicked');

  const ball = document.getElementById('ball');

  /* Setting random coordinates to demonstrate transition */
  ball.style.left = Number.parseInt(Math.random() * 200) + "px";
  ball.style.top = Number.parseInt(Math.random() * 200) + "px";
}

document.addEventListener("click", handleClick);
#field {
  position: relative;
  width: 100%;
  height: 100%;
}

/* Corrected to id selector with # rather than class selector 
   with . */
#ball {
  position: absolute;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #FF5722;
  position: absolute;

  /* Assigning transition behavior which is applied during 
     property changes */
  transition: all 3s ease-in-out;
}
<div id="field">
  <div id="ball"></div>
</div>

希望对您有所帮助