区域外点击隐藏

本文介绍了一种通过JavaScript/jQuery实现的区域外点击隐藏效果。该效果主要用于网页上浮动菜单或其他需要根据用户点击位置来显示或隐藏的元素。通过阻止特定区域内的点击事件冒泡,并监听整个容器的点击事件,可以实现当点击指定区域之外时隐藏该区域的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3  <head>
 4   <title>区域外点击隐藏</title>
 5   <meta name="generator" content="editplus" />
 6   <meta name="author" content="" />
 7   <meta name="keywords" content="" />
 8   <meta name="description" content="" />
 9  </head>
10  <style>
11     *{
12         padding:0px;
13         margin:0px;
14     }
15     .container{
16         position:absolute;
17         backgound-color:#e5e5e5;
18         width:100%;
19         height:100%;
20     }
21     .rightNav{
22         position:absolute;
23         right:0px;
24         width:200px;
25         height:100%;
26         background-color:#FFFFFF;
27         border:1px solid #e1e1e1;
28         box-shadow:-1px -1px 4px 0 rgba(153,153,153,0.50),1px 1px 4px 0 rgba(153,153,153,0.50);
29         border-radius:4px;
30     }
31  </style>
32  <body>
33     <div class="container">
34         <div class="rightNav">text</div>
35     </div>    
36     
37  </body>
38 </html>
39 <script src="./jquery-1.12.4.min.js"></script>
40 <script>
41     $(".container").click(function(e){
42     console.log(e.target);
43         //1.获取点击事件发生的对象
44         var target=$(e.target);
45         //2.判断是否发生在特定区域外
46         if(!target.is(".rightNav")){
47             //3.判断区域是否已经隐藏
48             if($(".rightNav").is(":visible")){
49                 //4.未隐藏则隐藏
50                 $(".rightNav").hide();
51             }
52         }
53     });
54     
55     //1.阻止右边栏点击事件冒泡
56     $(".rightNav").click(function(e){
57         console.log(e.stopPropagation());
58         alert(event.cancelBubble);
59         e?e.stopPropagation():event.cancelBubble=true;
60         
61     })
62     //2.外部点击区点击会让右边隐藏
63     $(".container").click(function(){
64         $(".rightNav").hide();
65     });
66 </script>
OutOfAreaClickHidden.html

 

转载于:https://www.cnblogs.com/lljboke/p/8847649.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值