<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脚本中的说明采用4s。不明白我做错了什么。
答案 0 :(得分: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>
答案 1 :(得分: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>