为什么这个过渡效果没有生效?

4
<html>

<head>
<title>Singularity</title>

<style>

body {
background-color: grey;
}

#boxOne {
position:relative;
height:150px;
width:150px;
background-color: black;

}

</style>
 <script>
  function playOne(){
  document.getElementById("boxOne").style.left = "30px";
  document.getElementById("boxOne").style.transition = "all 4s";
 }
 </script>


</head>

<body>
<div id="boxOne" onclick="playOne()"></div>
</body>
</html> 

以上代码在盒子从左到右移动方面可以正常工作。我以前成功地使用过style.transition,让一个圆从左到右缓慢移动,但是这个盒子的行为不像我想要的那样。盒子不应该立即从左到右移动,应该按照style.transition脚本中所述的4秒来移动。不明白我做错了什么。


不,它可以工作并正确地进行动画。https://jsfiddle.net/bx9x8c3y/ - nicael
不,它不会移动,而是立即从左到右。 - Ghoyos
抱歉,看起来在Safari中可以,在Chrome中不行。 - nicael
2个回答

5

您需要在样式表中设置一个起始值(所有浏览器都不会默认使用一个值)。

function playOne() {
  document.getElementById("boxOne").style.left = "30px";
  document.getElementById("boxOne").style.transition = "all 4s"; //might be coherent to declare this at first 
  //or even straight in the style sheet 
}
body {
  background-color: grey;
}
#boxOne {
  position: relative;
  height: 150px;
  width: 150px;
  left: 0;
  /* added this, so calculation can be done from an earlier css value*/
  background-color: black;
}
<div id="boxOne" onclick="playOne()"></div>


顺便说一下,初始示例在Safari中可以工作(因此并非所有浏览器都可以)。 - nicael
@nicael 我的意思是:won't == will not(英语不是我的母语,也没有学过,只是自己学的,所以我猜有时候听起来很滑稽 :)) - G-Cyrillus
GCyrillus,我非常感激!谢谢,现在它起作用了。现在我明白了为什么之前能让这个工作,因为那些其他页面有起始值。 - Ghoyos

1

您需要设置一个左侧的起始值,以使其正常工作

    <head>
<title>Singularity</title>

<style>

body {
background-color: grey;
}

#boxOne {
position:relative;
height:150px;
width:150px;
background-color: black;
left:0px; /*value left added*/

}

</style>
 <script>
  function playOne(){
  document.getElementById("boxOne").style.left = "250px";
  document.getElementById("boxOne").style.transition = "all 4s";
 }
 </script>


</head>

<body>
<div id="boxOne" onclick="playOne()"></div>
</body>
</html> 

谢谢你,奥萨马。在你回答之前,有人已经回答了,但你也是正确的。我非常感激你的帮助。 - Ghoyos
没问题,兄弟 :) - Muhammad Osama

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接