javascript - show and hide content by clicking button or background
问题描述
I tried to make a content, that gets viewed if you click a button an hides if you click that button again but also hides if you click anywhere else on the side except the content itself.
Like on www.w3schools.com if you click on tutorials.
my attempt was this:
$(":not(#content)").click
does not work. But even if, it would also get triggered all the times the content is not visible anyways. No good code.
$(document).ready(function() {
$("button").click(function() {
$("#content").toggle();
});
$(":not(#content)").click(function() {
$("#content").hide();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">This is the Content</div>
<button>switch</button>
<div> This is somewhere else </div>
解决方案
如果单击的元素不是按钮或包含在内容中,您可以向隐藏内容的文档添加单击事件侦听器。
$(document).ready(function() {
$("button").click(function() {
$("#content").toggle();
});
$(document).click(function(e) {
if(!$(e.target).closest('button, #content').length){
$('#content').hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content" style="display: none;">This is the Content</div>
<button>switch</button>
<div> This is somewhere else </div>
推荐阅读
- php - 多个文件上传而不在php中创建路障?
- web-services - org.apache.cxf.interceptor.Fault:意外元素/来自 WebSphere-7 的 WebSphere-Liberty 迁移
- javascript - 重新渲染视图而不重新加载/刷新 AngularJS 应用程序
- wordpress - WordPress 小文字问题
- sapui5 - UI5 中的 ComboBox 不显示 ValueState
- c# - System.OverflowException: '算术运算导致溢出。'
- google-apps-script - 谷歌脚本表单 ListItem:如何为每个选项设置 pageBreakItems?
- ios - Xcode 10.0 模拟器显示黑屏
- javascript - ChessboardJs:Javascript 棋盘只能在第一次使用
- java - 了解Java中序列化的重要性