单击栏或按钮外部时隐藏菜单侧栏

时间:2015-04-30 06:52:51

标签: javascript jquery html

我正在尝试创建一个类似语义UI的菜单,但我只是单击菜单按钮并打开菜单,反之亦然。我使用切换类来显示侧边栏,但我不知道这种方式是否完全正确:

<div class="menu-button" id="menu-button"></div>

$('#menu-button').click(function(event) {
     $('#hide-menu').toggleClass('show-menu');
});

.hide-menu {
    background-color:#336ca6;
    position: absolute;
    top:0;
    right:0;
    z-index: 1;
    width: 300px;
    height: 100%;
    -webkit-transform: translate3d(300px,0,0);
    -moz-transform: translate3d(300px,0,0);
    -o-transform: translate3d(300px,0,0);
    -ms-transform: translate3d(300px,0,0);
    transform: translate3d(300px,0,0);      
    -webkit-transition: all 0.3s linear;
    -moz-transition: all 0.3s linear;
    -ms-transition: all 0.3s linear;
    -o-transition: all 0.3s linear;
    transition: all 0.3s linear;
}

.show-menu {
    -webkit-transform: translate3d(0,0,0);
    -moz-transform: translate3d(0,0,0);
    -o-transform: translate3d(0,0,0);
    -ms-transform: translate3d(0,0,0);
    transform: translate3d(0,0,0);
 }  

I've tried the event propagation但我无法让它发挥作用。

5 个答案:

答案 0 :(得分:12)

将您的js代码编辑为以下

$('#menu-button').click(function(e){
    e.stopPropagation();
    $('#hide-menu').toggleClass('show-menu');
});

$('#hide-menu').click(function(e){
    e.stopPropagation();
});

$('body,html').click(function(e){
   $('#hide-menu').removeClass('show-menu');
});

希望这会奏效。

这是小提琴。 http://jsfiddle.net/ex8ddv5q/1/

答案 1 :(得分:4)

对于不同的选择,请查看此Fiddle

$('#menu-button').click(function (evt) {
    evt.stopPropagation();
    $('#hide-menu').toggleClass('show-menu');
});


$('body,html').click(function (e) {

    var container = $("#hide-menu");

    if (!container.is(e.target) && container.has(e.target).length === 0) {
        container.removeClass('show-menu');

    }
});

答案 2 :(得分:2)

如果有人来到这里并且正在使用Angular而不是JQuery,我们可以使用类似于上面的内容:

public toggleSideNav() {
    this.showSideNav = !this.showSideNav;
    console.log('show side nav', this.showSideNav);
    event.stopPropagation();
}

public hideSideNav() {
    this.showSideNav = false;
    console.log('hide side nav');
}

这在模板中:

<app-sidenav></app-sidenav>
<div class="main-body" (click)="applicationService.hideSideNav()">
    <router-outlet></router-outlet>
</div>

答案 3 :(得分:1)

假设边栏宽度为270px,请检查鼠标单击坐标。如果更大,则将其left样式属性设置为-270px;

function handleMousePos(event) {
      var mouseClickWidth = event.clientX;
      if(mouseClickWidth>=270){
            document.getElementById("mySidenav").style.left='-270px'
           }
}

document.addEventListener("click", handleMousePos);

这是我的示例:https://codepen.io/johncy/pen/oMyzZr

答案 4 :(得分:0)

$('body').click(function(){
     $('#hide-menu').removeClass('show-menu');
});