jQuery toggle DIV - 单击元素时重置切换

时间:2014-06-29 08:21:45

标签: javascript jquery html css html5

我尝试实施滑出式菜单,但在单击完整面板时我无法取消切换效果。

我使用Menu锚来初始化切换。出现滑出菜单时,完整面板的不透明度会下降。我希望用户只需单击整个面板上的任意位置即可取消切换并返回原始状态。

JSFiddle:http://jsfiddle.net/q2tcE/

jQuery的:

$('.menu-nav').toggle(

function () {

    $('.full_panel').animate({
        width: "75%",
        opacity: 0.20
    }, 500);

    $('.aside-panel').animate({
        width: "25%"
    }, 500);

},

function () {

    $('.full_panel').animate({
        width: "100%",
        opacity: 1
    }, 500);

    $('.aside-panel').animate({
        width: "0%"
    }, 500);
});

HTML:

<div class="header"></div>

<div class="full_panel">
    <a href="#" class="menu-nav">Menu</a>
</div>

<div class="aside-panel"></div>

<div class="clearfix"></div>

CSS:

html, body{height: 100%; margin: 0; background:#2980b9 }

.header{background: #BADA55; padding: 20px; background: #2980b9}

.full_panel{
    background-color: rgba(0,0,0,0.2);
    width: 100%;
    height: 100%;
    float: left;
}

.aside-panel{
    background-color: rgba(0,0,0,0.7);
    width: 0%;
    height: 100%;
    float: left;
}

.clearfix{clear: both}

a{color: #CCC; text-decoration: none; }

2 个答案:

答案 0 :(得分:1)

只需使用两个功能:

   function togglePanel() {
    $('.menu-nav').toggle(
    function () {
        $('.full_panel').animate({
            width: "75%",
            opacity: 0.20
        }, 500);
        $('.aside-panel').animate({
            width: "25%"
        }, 500);
    },
    function () {
        $('.full_panel').animate({
            width: "100%",
            opacity: 1
        }, 500);
        $('.aside-panel').animate({
            width: "0%"
        }, 500);
    });
}
function togglePanelReverse() {
    $('.full_panel').animate({
        width: "100%",
        opacity: 1
    }, 500);
    $('.aside-panel').animate({
        width: "0%"
    }, 500);
}
$('.full_panel').click(function () {
    togglePanelReverse();
});
togglePanel();

答案 1 :(得分:0)

您必须将一个点击处理程序添加到要切换回来的div:

$('.menu-nav').toggle(function () {
  $('.full_panel').animate({
    width: "75%",
    opacity: 0.20
  }, 500);

  $('.aside-panel').animate({
    width: "25%"
  }, 500);

});

$('.full_panel').click(function() {  
    $('.full_panel').animate({
        width: "100%",
        opacity: 1
    }, 500);
    $('.aside-panel').animate({
        width: "0%"
    }, 500);
});