我在删除使用 JavaScript 创建的 div 元素时遇到了麻烦。我将此函数称为 onclick 元素。
function makediv(){
var div = document.createElement('DIV');
$(div).attr('id','md');
$(div).css({"left":e.pageX,"top":e.pageY });
$("body").append(div);
}
当我单击该 div 以外的其他位置时,我将如何尝试删除它。 在我点击其他地方之前,div 甚至出现了,它在创建时就被删除了。
window.onclick = function(event)
{
dl=$('#md');
if(event.target!=dl)
dl.remove();
}
我也尝试过这个。
window.onclick = function(event)
{
if($('#md').length!=0){
dl=$('#md');
if(event.target!=dl)
dl.remove();
}
}
但是此代码在创建 div 元素时将其删除。
最佳答案
您可以使用 jQuery
来编写更短、更简单的代码。
function makediv() {
$("body").append("<div id='md'></div>");
}
$(document).ready(function() {
makediv(); /* Call the function to add the div */
});
$(document).click(function(e) {
/* Check if id is mb. If it is not, remove the div */
if ($(e.target).attr("id") != "md") $("#md").remove();
});
#md {
width: 100px;
height: 100px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
关于javascript - 单击 div 元素以外的任何位置时删除该 div 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48789074/