【问题标题】:remove a div element when clicking anywhere else than that div element [duplicate]单击 div 元素以外的任何其他位置时删除 div 元素[重复]
【发布时间】:2018-02-14 14:02:37
【问题描述】:

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

【问题讨论】:

  • 你能贴出你的html代码吗
  • "但此代码在创建时删除了 div 元素。"你什么意思?
  • 我想在单击该 div 以外的其他位置时将其删除。但是这段代码在创建它时删除了 div,它甚至没有出现。
  • 不要使用if(event.target!=dl),而是尝试使用if(!$(event.target).is(dl))

标签: javascript jquery html


【解决方案1】:

您可以使用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;
}
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 我会考虑在红色的后面创建一个绝对定位的全屏透明 div 并将事件添加到它而不是整个页面元素
  • 谢谢,我认为这是最好的解决方案。
  • 乐于帮助@AdeelApple
猜你喜欢
  • 2012-09-25
  • 1970-01-01
  • 2020-09-05
  • 2021-08-26
  • 2014-09-07
  • 2021-02-18
  • 1970-01-01
  • 2013-03-29
  • 2017-09-16
相关资源
最近更新 更多