单击除div元素以外的任何位置时删除div元素

时间:2018-02-14 14:02:38

标签: javascript jquery html html5

我在删除使用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元素。

1 个答案:

答案 0 :(得分:0)

您可以使用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();
});
&#13;
#md {
  width: 100px;
  height: 100px;
  background-color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
&#13;
&#13;
&#13;