本文介绍了点击外面时隐藏div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个简单的JavaScript代码来切换div onclick。你可以在这个链接上看到它:k-prim.biz/Untitled-2.html - 这是一个非常简单的演示页面。我想做的是不仅在点击链接时隐藏div,而且在div外部点击时也是如此。另外,当div显示时,如何更改链接的CSS样式?提前谢谢!

I am using a simple javascript code to toggle div onclick. You can see it in action on this link: k-prim.biz/Untitled-2.html - it is a quite simple demo page. What I want to make is to hide div not only when click on the "link" but also when click outside the div. Also how can I change the css style of the "link" when the div is displayed? Thank you in advance!

<script type="text/javascript" language="javascript">
   function showHide() {
   var ele = document.getElementById("showHideDiv");
if(ele.style.display == "block") {
        ele.style.display = "none";
  }
else {
    ele.style.display = "block"; }
}
</script>
<a href="#" onClick="return showHide();" >link</a>
<div id="showHideDiv" style="display:none;">hello!</div>


推荐答案

你没有给我任何代码可以使用,所以你必须修改它以满足你的需要:

You've not given me any code to work with, so you'll have to modify this to suit your needs:

$(document).click(function() {
    if(this != $("#the_div")[0]) {
        $("#the_div").hide();
    }
});

如果用户点击页面上不是div的任何地方,那么将隐藏div。

That will hide the div if a user clicks anywhere on the page that isn't that div.

这篇关于点击外面时隐藏div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:25