Jquery:菜单会在几秒钟后自动滑到一边

时间:2015-03-25 10:18:17

标签: javascript jquery menu slide

以下代码执行此操作:访问者点击菜单,从左侧水平滑动。访问者再次点击菜单,它会滑出(关闭)。

我想要的是:同样的行为。但是:如果菜单打开且访问者没有点击任何地方,菜单会在5秒后滑出(关闭)。

感谢您的帮助!

var clicked = 0;
function header() {
$('#header').click(
    function(){
            if(clicked === 0){
                $(this).stop().animate({ paddingLeft: '230px'}, {queue: false, duration: 400 });
                clicked = 1;
            } else if(clicked === 1){
                $(this).stop().animate({ paddingLeft: '0'});  
                clicked = 0;
            }
        }
);
}

1 个答案:

答案 0 :(得分:3)

使用.setTimeout()功能:

setTimeout(function() {
    // your animation
}, 2000);

您的整个代码应该看起来像这样:

// You use the "clicked" variable to check if the menu is already active or not
var clicked = false;

// You can delete the "function header()" part because it's unnecessary

// Here we add "click" event when the visitor clicks the header
$('#header').click(function(){

    // Check if menu is already active
    if(clicked == false){
        // If not: animate menu and make active (*see below for more info)
        $(this).stop().animate({ paddingLeft: '230px'}, {queue: false, duration: 400 });
        clicked = true;

    } else {
        // If yes: animate menu back to normal and make inactive
        $(this).stop().animate({ paddingLeft: '0'});  
        clicked = false;
    }
});

// Set header to automatically animate to active after 2000 milliseconds
setTimeout(function() {
    $("#header").stop().animate({ paddingLeft: '230px'}, {queue: false, duration: 400 });
    clicked = true;
}, 2000);

我也为你当前的代码添加了解释。有关此.animate()功能的更多信息:http://api.jquery.com/animate/