[英]What is the best way to achieve updating a DOM element with vanilla Javascript?
我想要一個使用香草javascript執行以下操作的div:
取消也會在途中逐漸消失,因此,如果用戶快速單擊一個按鈕20次,則不會在最近一次出現20次淡入/淡出。
這是我現在所在的位置: https : //jsfiddle.net/d685Ledu/
<body>
<div id="wrapper">
<p>Content content</p>
</div>
<button id="button">click me</button>
</body>
<script type="text/javascript">
var wrapper = document.getElementById('wrapper');
var fadeSpeed = 0.01;
document.getElementById('button').addEventListener('click', function(){
fadeOut();
updateDiv();
moveDiv();
fadeIn();
});
function updateDiv() {
wrapper.innerHTML= '<div>lots</div><div>of</div><div>new</div><div>content</div>';
}
function moveDiv() {
wrapper.style.top = '100px';
wrapper.style.left = '100px';
}
function fadeIn() {
var opacity = 0;
function increase() {
opacity += fadeSpeed;
if (opacity >= 1){
wrapper.style.opacity = 1;
return true;
}
wrapper.style.opacity = opacity;
requestAnimationFrame(increase);
}
increase();
}
function fadeOut() {
var opacity = 1;
function decrease() {
opacity -= fadeSpeed;
if (opacity <= 0){
wrapper.style.opacity = 0;
return true;
}
wrapper.style.opacity = opacity;
requestAnimationFrame(decrease);
}
decrease();
}
</script>
實現這一目標的最慣用的方法是什么?
如果您只是嘗試更新特定的div,則需要更新margin-left
和margin-right
。
話雖如此,將您的moveDiv
函數更改為:
function moveDiv() {
wrapper.style["margin-left"]="100px";
wrapper.style["margin-top"]="100px";
}
就像我在第二條評論中所說的那樣,我強烈建議您研究一下框架。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.