在JavaScript中将元素的高度设置为0然后立即将其更改为特定值时,元素的CSS转换不起作用.
但是,通过放置代码来增加a内的高度setTimeout(),即使延迟为0,转换仍然有效,如下面的代码片段所示:
// Doesn't work:
document.getElementById("one").setAttribute("style", "height: 0px");
document.getElementById("one").setAttribute("style", "height: 200px");
// Works:
document.getElementById("two").setAttribute("style", "height: 0px");
setTimeout(function() {
document.getElementById("two").setAttribute("style", "height: 200px");
}, 0);Run Code Online (Sandbox Code Playgroud)
div {
display: inline-block;
width: 200px;
background-color: black;
transition: height 1s;
}
#two {
background-color: blue;
}Run Code Online (Sandbox Code Playgroud)
<div id="one">
</div>
<div id="two">
</div>Run Code Online (Sandbox Code Playgroud)
此行为在所有主流浏览器中都是一致的.这个问题是,有时似乎存在某种延迟,这使得解决方法也不具有动画效果.所以这似乎不是一个干净的解决方案.
导致过渡取消的原因是什么?我如何干净利落地解决这个问题?
我是JavaScript新手,我想从我的数组中获取三个随机元素,这些元素需要不同.我已经设法得到三个不同的元素,然后我尝试通过split方法只获取一个元素.但显然这不起作用,可能有很多错误,因为这是我的第一个脚本之一.它有时也说"未定义".
HTML:
<span id="tot1"></span>, <span id="tot2"> und </span> und <span id="tot3"></span>
Run Code Online (Sandbox Code Playgroud)
使用Javascript:
function getNumber() {
random = Math.floor(Math.random() * students.length);
students.splice(random,1);
return random;
}
students = new Array("Paul", "Jan", "Fabian D.", "Fabian K.", "Lennard",
"Robin", "Angelique", "Joyce", "Sarah", "Ajlin",
"Enes", "Leon", "Boran", "Joshua")
getNumber();
tot1 = students[random];
getNumber();
tot2 = students[random];
getNumber();
tot3 = students[random];
document.getElementById('tot1').innerHTML = tot1;
document.getElementById('tot2').innerHTML = tot2;
document.getElementById('tot3').innerHTML = tot3;
Run Code Online (Sandbox Code Playgroud)