简体   繁体   中英

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

I am trying to make the div hide but it does not. 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

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

<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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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