我试图通过使用javascript更改高度来触发元素的过渡效果。我已经找到了答案,但我找到的只是使用css动画而我的代码与这个想法不兼容。这是我的代码;
function printVolumeLevel(level) {
var volumeDiv = document.getElementById('volume_level');
volumeDiv.innerHTML = "";
var iconVolume = document.getElementById('icon_volume');
iconVolume.innerHTML = "";
if (OutputSettings.isAudioMuted() === false) {
iconVolume.innerHTML += "<div class=\"volumeOn\" /> \n";
volumeDiv.innerHTML += "<div class=\"volumeLevelUnfocus\" /> \n";
volumeDiv.innerHTML += "<div class=\"volumeLevelFocus\" /> \n";
var volumeHeight = level * 40;
document.getElementsByClassName("volumeLevelFocus")[0].style.height = volumeHeight + "px";
document.getElementsByClassName("volumeLevelUnfocus")[0].style.height = (800 - volumeHeight) + "px";
} else {
iconVolume.innerHTML += "<div class=\"volumeOff\" /> \n";
document.getElementsByClassName("volumeLevelUnfocus")[0].style.setProperty("height", "800px");
}
}
.volumeLevelFocus {
background: #da1c5c;
width: 40px;
-webkit-transition: height 0.2s;
transition: height 0.2s;
-webkit-transition: width 0.2s;
transition: width 0.2s;
height: 400px;
}
.volumeLevelUnfocus {
background: #111a21;
width: 40px;
-webkit-transition: height 0.2s;
transition: height 0.2s;
height: 400px;
}
<div id="volume_level"></div>
答案 0 :(得分:2)
您的代码中存在多个问题:
您无法按/>
关闭div,它会被</div>
关闭。
要在html中换行,您必须使用<br>
而不是&#34; \ n&#34;
您没有添加div id="icon_volume"
。
如果要添加元素并通过转换更改其样式,则必须使用其他进程完成更改(在答案setTimeot中);
你的代码是这样的:
Insert_a_div_with_height(0像素);
Make_the_height_of_Inserted_div(800像素);
它只添加一个高度为800px的div ,因此没有样式更改,因此没有转换。
以下是一个简单的答案:
.volumeLevelUnfocus {
background: #111a21;
width: 40px;
transition-duration: 5s;
height:400px;
}
&#13;
<div id="volume_level"></div>
<script>
var volumeDiv = document.getElementById('volume_level');
volumeDiv.innerHTML = "";
volumeDiv.innerHTML += "<div class=\"volumeLevelUnfocus\" style='height:0px;'></div>";
//another process to change the height of inserted div:
setTimeout(function(){
document.getElementsByClassName("volumeLevelUnfocus")[0].style.height = "800px";
}, 100);
</script>
&#13;