它正在作業,但是當單擊關閉圖示時它不會洗掉
我不知道我該怎么做!!!因為我正在做自定義警報框并且我正在做這個
創建div而不是洗掉
我想關閉/洗掉div元素和div在createElement();功能
,我嘗試W3Schools的和堆疊溢位的問題
,但仍然沒有作業
,我不知道為什么
這是我的代碼:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Custom Alert Box</title>
</head>
<body>
<button onclick="alert('hello')">Try it</button>
<script>
alert = function(arguments) {
var alertbox = document.createElement("div");
var close = document.createElement("img");
var text = document.createTextNode(arguments);
alertbox.setAttribute("style", `
border: 0.8px solid #002;
border-radius: 4px;
box-shadow: 0 2px 4px #454c4e;
padding: 6px;
height: 80px;
`
);
close.setAttribute("style", `
width: 18px;
height: auto;
float: right;
`
);
close.setAttribute("src", "https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-close-512.png");
close.setAttribute("alt", "close");
close.setAttribute("onclick", alertbox.remove()); // The Close Icon That Removes/Closes The Div
alertbox.appendChild(text);
alertbox.appendChild(close)
document.body.appendChild(alertbox);
}
</script>
</body>
</html>```
uj5u.com熱心網友回復:
您應該添加一個 eventListener 而不是 setattribute。代替 :
close.setAttribute("onclick", alertbox.remove());
利用 :
close.addEventListener("click", () => { alertbox.remove();})
uj5u.com熱心網友回復:
如果我理解你的問題,你想從 DOM 中洗掉一個 div。
- 獲取對該元素的參考
document.querySelector() - 獲取結果的父元素
myelement.parentElement - 使用方法洗掉元素
parent.removeChild()
另一種解決方案是在創建元素后隱藏元素(display: none例如,使用CSS 屬性)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/386923.html
標籤:javascript html css
