javascript - 如何通过点击外部关闭导航栏?
问题描述
我有一个带有 Bootstrap 3.3.7 主题的 Drupal 8.6.8 站点
当我点击外部时,我希望我的导航菜单关闭。我尝试了代码:
(function ($) {
'use strict';
$(document).click(function (event) {
if (!$(event.target).closest('#navbar-collapse-first').length) {
$('.navbar-collapse-first').collapse('hide');
}
});
$(document).click(function (event) {
if (!$(event.target).closest('#navbar-collapse-second').length) {
$('.navbar-collapse-second').collapse('hide');
}
});
}(jQuery));
https://css-tricks.com/dangers-stopping-event-propagation/
它不起作用,如果我在导航菜单之外单击,它不起作用 此代码仅在我删除第二个或离开第二个并删除第一个时才有效。
如何在 2 菜单上应用这个?
更新 :
我找到了答案:
(function ($) {
'use strict';
$(document).click(function (event) {
if (!$(event.target).closest('#navbar-collapse-first').length) {
$('.navbar-collapse-first').collapse('hide');
}
if (!$(event.target).closest('#navbar-collapse-second').length) {
$('.navbar-collapse-second').collapse('hide');
}
});
}(jQuery));
解决方案
您可以使用此功能
function OnwindowClick(elem , action){
$(document).on('click',function(e){
if (!$(elem).is(e.target) // if the target of the click isn't the container...
&& $(elem).has(e.target).length === 0) // ... nor a descendant of the container
{
action();
}
});
}
并像使用它一样
// OnwindowClick(elem , action) add the prevent elements in `elem` something like this
OnwindowClick('#navbar-collapse-first , #navbar-collapse-second', function(){
$('.navbar-collapse-first, .navbar-collapse-second').collapse('hide');
});
笔记:
无需
.closest()
直接使用选择器elem
是防止文档点击它的元素
附加:您仍然需要将按钮添加到elem
..#navbar-collapse-first , #navbar-collapse-second , button1_Selector , button2_Selector
如何使用此功能的示例
$(document).ready(function(){
$('button.clickable').on('click' , function(){
$(this).text($(this).text() == 'Like' ? 'Dislike' : 'Like');
});
OnwindowClick('button.clickable' , function(){
$('button.clickable').fadeOut(400);
setTimeout(function(){
$('button.clickable').fadeIn(400);
} , 5000);
});
});
function OnwindowClick(elem , action){
$(document).on('click',function(e){
if (!$(elem).is(e.target) // if the target of the click isn't the container...
&& $(elem).has(e.target).length === 0) // ... nor a descendant of the container
{
action();
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="clickable">Like</button>
推荐阅读
- html - Flexbox 使用相同大小的元素证明包装内容的合理性
- javascript - 获取 Json 数据并在拆分窗口上显示 onclick html
- arrays - 如何使用一组元素初始化特定的 numpy 数组元素值?
- python - 在可编辑的 QSqlQueryModel 中实现 setEditStrategy
- javascript - 将 Mocha api 测试从异步等待转换为 Supertest
- mongodb - 如何从 Mongoose 获取 MongoClient 对象?
- kotlin - JPA - 使用参数值作为选择的回报
- xamarin.forms - 拨打号码并返回应用程序
- mysql - 如何使用 django mysql 在原始 sql 查询中传递动态变量
- google-sheets - 为每个字符串的出现次数突出显示不同颜色的单元格