最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to close drop down by clicking anywhere on page? - Stack Overflow

programmeradmin1浏览0评论

Below is a simple code for javascript dropdown menu given by w3schools, I wanted two dropdowns so I created a duplicate with changed element and variable names. Both dropdowns work fine except now I can't close opened drop down by clicking anywhere on web page which worked fine with one dropdown. So how can I make that work while having two drop downs.

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}


/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction2() {
  document.getElementById("myDropdown2").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn2')) {

    var dropdown = document.getElementsByClassName("dropdown-content2");
    var e;
    for (e = 0; i < dropdown.length; e++) {
      var opendropdown = dropdown[e];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
/* Dropdown Button */

.dropbtn {
  background-color: #4CAF50;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}
/* Dropdown button on hover & focus */

.dropbtn:hover,
.dropbtn:focus {
  background-color: #3e8e41;
}
/* The container <div> - needed to position the dropdown content */

.dropdown {
  position: relative;
  display: inline-block;
}
/* Dropdown Content (Hidden by Default) */

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}
/* Links inside the dropdown */

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}
/* Change color of dropdown links on hover */

.dropdown-content a:hover {
  background-color: #f1f1f1
}
/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */

.show {
  display: block;
}
/* Dropdown Button */

.dropbtn2 {
  background-color: #4CAF50;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}
/* Dropdown button on hover & focus */

.dropbtn2:hover,
.dropbtn2:focus {
  background-color: #3e8e41;
}
/* The container <div> - needed to position the dropdown content */

.dropdown2 {
  position: relative;
  display: inline-block;
}
/* Dropdown Content (Hidden by Default) */

.dropdown-content2 {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}
/* Links inside the dropdown */

.dropdown-content2 a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}
/* Change color of dropdown links on hover */

.dropdown-content2 a:hover {
  background-color: #f1f1f1
}
/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */

.show {
  display: block;
}
<script src=".11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <div class="dropdown">
        <button onclick="myFunction()" class="dropbtn">Dropdown</button>
        <div id="myDropdown" class="dropdown-content">
          <a href="#">Link 1</a>
          <a href="#">Link 2</a>
          <a href="#">Link 3</a>
        </div>
      </div>
    </td>
    <td>
      <div class="dropdown2">
        <button onclick="myFunction2()" class="dropbtn">Dropdown2</button>
        <div id="myDropdown2" class="dropdown-content2">
          <a href="#">Link 1</a>
          <a href="#">Link 2</a>
          <a href="#">Link 3</a>
        </div>
      </div>
    </td>
  </tr>
</table>

Below is a simple code for javascript dropdown menu given by w3schools, I wanted two dropdowns so I created a duplicate with changed element and variable names. Both dropdowns work fine except now I can't close opened drop down by clicking anywhere on web page which worked fine with one dropdown. So how can I make that work while having two drop downs.

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}


/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction2() {
  document.getElementById("myDropdown2").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn2')) {

    var dropdown = document.getElementsByClassName("dropdown-content2");
    var e;
    for (e = 0; i < dropdown.length; e++) {
      var opendropdown = dropdown[e];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
/* Dropdown Button */

.dropbtn {
  background-color: #4CAF50;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}
/* Dropdown button on hover & focus */

.dropbtn:hover,
.dropbtn:focus {
  background-color: #3e8e41;
}
/* The container <div> - needed to position the dropdown content */

.dropdown {
  position: relative;
  display: inline-block;
}
/* Dropdown Content (Hidden by Default) */

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}
/* Links inside the dropdown */

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}
/* Change color of dropdown links on hover */

.dropdown-content a:hover {
  background-color: #f1f1f1
}
/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */

.show {
  display: block;
}
/* Dropdown Button */

.dropbtn2 {
  background-color: #4CAF50;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}
/* Dropdown button on hover & focus */

.dropbtn2:hover,
.dropbtn2:focus {
  background-color: #3e8e41;
}
/* The container <div> - needed to position the dropdown content */

.dropdown2 {
  position: relative;
  display: inline-block;
}
/* Dropdown Content (Hidden by Default) */

.dropdown-content2 {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}
/* Links inside the dropdown */

.dropdown-content2 a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}
/* Change color of dropdown links on hover */

.dropdown-content2 a:hover {
  background-color: #f1f1f1
}
/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */

.show {
  display: block;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <div class="dropdown">
        <button onclick="myFunction()" class="dropbtn">Dropdown</button>
        <div id="myDropdown" class="dropdown-content">
          <a href="#">Link 1</a>
          <a href="#">Link 2</a>
          <a href="#">Link 3</a>
        </div>
      </div>
    </td>
    <td>
      <div class="dropdown2">
        <button onclick="myFunction2()" class="dropbtn">Dropdown2</button>
        <div id="myDropdown2" class="dropdown-content2">
          <a href="#">Link 1</a>
          <a href="#">Link 2</a>
          <a href="#">Link 3</a>
        </div>
      </div>
    </td>
  </tr>
</table>

Share Improve this question edited Mar 10, 2016 at 11:45 Praveen Kumar Purushothaman 167k27 gold badges213 silver badges259 bronze badges asked Mar 10, 2016 at 11:41 bɪˈɡɪnəbɪˈɡɪnə 1,0852 gold badges25 silver badges48 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You can do like following way. No need to write that code to remove class as you toggle class.

Just remove on window click.

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction(event) {
  event.stopPropagation();
  document.getElementById("myDropdown").classList.toggle("show");
}

function myFunction2(event) {
  event.stopPropagation();
  document.getElementById("myDropdown2").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  document.getElementById("myDropdown").classList.remove("show");
  document.getElementById("myDropdown2").classList.remove("show");
}
/* Dropdown Button */

.dropbtn {
  background-color: #4CAF50;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}
/* Dropdown button on hover & focus */

.dropbtn:hover,
.dropbtn:focus {
  background-color: #3e8e41;
}
/* The container <div> - needed to position the dropdown content */

.dropdown {
  position: relative;
  display: inline-block;
}
/* Dropdown Content (Hidden by Default) */

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}
/* Links inside the dropdown */

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}
/* Change color of dropdown links on hover */

.dropdown-content a:hover {
  background-color: #f1f1f1
}
/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */

.show {
  display: block;
}
/* Dropdown Button */

.dropbtn2 {
  background-color: #4CAF50;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}
/* Dropdown button on hover & focus */

.dropbtn2:hover,
.dropbtn2:focus {
  background-color: #3e8e41;
}
/* The container <div> - needed to position the dropdown content */

.dropdown2 {
  position: relative;
  display: inline-block;
}
/* Dropdown Content (Hidden by Default) */

.dropdown-content2 {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}
/* Links inside the dropdown */

.dropdown-content2 a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}
/* Change color of dropdown links on hover */

.dropdown-content2 a:hover {
  background-color: #f1f1f1
}
/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */

.show {
  display: block;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <div class="dropdown">
        <button onclick="myFunction(event)" class="dropbtn">Dropdown</button>
        <div id="myDropdown" class="dropdown-content">
          <a href="#">Link 1</a>
          <a href="#">Link 2</a>
          <a href="#">Link 3</a>
        </div>
      </div>
    </td>
    <td>
      <div class="dropdown2">
        <button onclick="myFunction2(event)" class="dropbtn">Dropdown2</button>
        <div id="myDropdown2" class="dropdown-content2">
          <a href="#">Link 1</a>
          <a href="#">Link 2</a>
          <a href="#">Link 3</a>
        </div>
      </div>
    </td>
  </tr>
</table>

With the help of jquery it is possible to prepare function for handling click outside some element in following way

function outsideElementClickEvent(elm, callback) {
    function isClickedOutside(e){
        var container = $(elm);

        if (!container.is(e.target) // if the target of the click isn't the container...
            && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
            callback();
        }
    }

    $(document).mouseup(isClickedOutside);
    return isClickedOutside;
},

/**
 * It removes outside element handler passed in as a parameter.
 *
 * @param handler
 */
function removeOutsideElementHandler(handler) {
    if (handler) {
        $(document).unbind("mouseup", handler);
    }
}
发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>