简体   繁体   English

为什么在div外部单击时div无法隐藏?

[英]Why does the div not hide when clicking outside of it?

I am trying to make the div hide but it does not. 我正在尝试使div隐藏,但事实并非如此。 Here is a meteor pad showing the problem. 是显示问题的流星垫。

How can it be made to hide after clicking outside of it. 在其外部单击后如何隐藏它。

Here is the code if the meteor pad does not load 如果流星垫未加载,这是代码

JS JS

if (Meteor.isClient) {
  Template.hello.events({
    'click #loginbntstoggle' : function(e){
        if(document.getElementById("textoneandtwo").style.display=="none"){
            document.getElementById("logitextoneandtwonbnts").style.display = "block";
        }else{
            document.getElementById("textoneandtwo").style.display = "none";
        }
    },

  'click body' : function(e){
    if(e.target.className !== "textoneandtwo")
    {
      document.getElementById("textoneandtwo").style.display = "none";
    }
  }
});
}

HTML 的HTML

<head>
  <title>test</title>
</head>

<body>
  <h1>Welcome to Meteor!</h1>

  {{> hello}}
</body>

<template name="hello">

<button id="onoroff"
        class="mdl-button mdl-js-button mdl-button--icon">
  <i class="material-icons">more_vert</i>
</button>

<div id="textoneandtwo" style="display: none;">
    <form action="#">
        <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
                <input class="mdl-textfield__input" type="text" id="sample3" />
            <label class="mdl-textfield__label" for="sample3">Text...</label>
        </div>

        <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
                <input class="mdl-textfield__input" type="text" id="sample3" />
            <label class="mdl-textfield__label" for="sample3">Text...</label>
        </div>
    </form>
</div>

</template>

I think below code can help you. 我认为以下代码可以为您提供帮助。 Just put your div element id in below code: 只需将您的div元素ID放在以下代码中:

function bodyClickHandller(evt){
    if(!($.contains(divElement, evt.target)) || (divElement == evt.target))){
        $(divElement).hide();
    }
}
$("body").off("click").on("click", bodyClickHandller);
var divElement = document.getElementById("div_element_id");

Please let me know if you will face any issue. 如果您遇到任何问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM