[英]How to undo a JavaScript function? The first function works, but I want to undo it with the second function, but that one does not work
<script>
const elem= document.getElementById("close");
以下 function 像我想要的那樣刪除了div
容器:
window.onload = function(){
document.getElementById("close").onclick = function(){
this.parentNode.parentNode.parentNode
.removeChild(this.parentNode.parentNode);
return false;
};
};
下面的 function 應該在用戶滾動回頂部時自動撤消第一個 function 的效果,但它不起作用。
window.addEventListener('scroll', function() {
document.getElementById('showScroll').innerHTML = window.pageYOffset;
if (window.pageYOffset===0){
document.getElementById("close")=elem;
}
return false;
});
</script>
主要問題在於這一行:
document.getElementById("close")=elem;
它應該是這樣的:
document.getElementById("container").appendChild(elem);
問題是id
為close
的元素不再在 DOM 中(單擊按鈕時它已被刪除),因此一旦它消失,您就無法在代碼中引用它。
因此,您需要將其父元素(例如container
)和elem
按鈕元素作為子元素引用到container
。 如果elem
不在container
的末尾,那么您必須找出 append 的位置。
但是,第一個代碼中也有多個parentNodes
,這可能不是必需的。
這是一個詳細的參考: MDN Node.appendChild()
這是一個演示,向您展示了這項工作:
const elem = document.getElementById("close"); window.onload = function() { document.getElementById("close").onclick = function() { this.parentNode.removeChild(this); }; }; window.addEventListener('scroll', function() { document.getElementById("showScroll").textContent = 'scrollY: ' + Math.floor(window.pageYOffset); if (window.pageYOffset === 0) { document.getElementById("container").appendChild(elem); } });
#container { border: solid 3px red; padding: 10px; } #showScroll { position: fixed; top: 0px; margin-left: 100px; background: yellow; }
<div id="container"> <p id="showScroll">scrollY: 0</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <p>Test</p> <button id="close"> Close </button> </div>
如果你使用這個:
this.parentNode.parentNode.removeChild(this.parentNode);
那么它的反面是這樣的:
this.parentNode.parentNode.appendChild(element);
所以總結一下:
// this will remove the element but keep it saved inside elem
let keep = this.parentNode.parentNode.removeChild(this.parentNode);
// this will place back the element you removed
this.parentNode.parentNode.appendChild(keep);
那是因為document.getElementById("close")
已經被刪除了。
如果您無論如何要插入該元素,一個更好的解決方案是使用它的 css。
只需在其 css 中添加display:none
,該元素將與消失相同(實際上並未被刪除)。
// hide the element without deleting it
document.getElementById("close").style.display = "none";
// make the element visible again
document.getElementById("close").style.display = "block";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.