遵循 this CSS Tricks article 的建议,我尝试编写一些代码来使用 JavaScript 引发 CSS 转换。
(这是我的 jsFiddle .)
HTML:
<button id="button" onclick="doMove2()" value="play">Play</button>
<div class="foo"></div>
CSS:
#button {
position: absolute;
width: 200px;
height: 50px;
top: 185px;
left: 0px;
}
.foo {
position: absolute;
width: 50px;
height: 50px;
border: 1px dashed black;
left: 0px;
top: 120px;
}
.foo.horizTranslate {
-webkit-transition: 3s;
-moz-transition: 3s;
-ms-transition: 3s;
-o-transition: 3s;
transition: 3s;
margin-left: 50% !important;
}
JavaScript:
var foo = document.getElementsByClassName('foo')[0];
function doMove2(){
document.getElementById("button").onclick = function(){
if(this.innerHTML === 'Play'){
this.innerHTML = 'Pause';
foo.classList.add('horizTranslate');
} else {
this.innerHTML = 'Play';
var computedStyle = window.getComputedStyle(foo2),
marginLeft = computedStyle.getPropertyValue('margin-left');
foo.style.marginLeft = marginLeft;
foo.classList.remove('horizTranslate');
}
}
}
为什么这行不通?
谁能解释一下过渡和动画之间的区别?
最佳答案
首先,我不推荐使用 jsfiddle,有时它会出现故障且不可靠。我使用 jsbin,查看我的演示:http://jsbin.com/guceneku/1/
我删除了你的 HTML 标签中的 onclick,因为你已经在 js 中有一个触发器,所以它变成了:
<button id="button" value="play">Play</button>
<div class="foo"></div>
接下来你的js变成:
var foo = document.getElementsByClassName('foo')[0];
document.getElementById("button").onclick = function(){
if(this.innerHTML === 'Play'){
this.innerHTML = 'Pause';
foo.classList.add('horizTranslate');
} else{
this.innerHTML = 'Play';
var computedStyle = window.getComputedStyle(foo2),
marginLeft = computedStyle.getPropertyValue('margin-left');
foo.style.marginLeft = marginLeft;
foo.classList.remove('horizTranslate');
}
}
关于JavaScript 诱导的 CSS 动画不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25245370/