简体   繁体   English

脚本只运行一次

[英]Script running only once

I'm trying to make a side menu that opens and closes from the left when you press the menu button. 当我按下菜单按钮时,我正在尝试制作一个从左侧打开和关闭的侧边菜单。 Got the css, html code running properly but I can't figure out what I'm doing wrong with the script. 得到了css,html代码正常运行,但我无法弄清楚我对脚本做错了什么。 It works perfectly but only once: When I press the menu button it comes out, press it again and it goes back just as intended. 它只能完美地工作一次:当我按下菜单按钮它出来时,再次按下它然后按照预期返回。 The problem is if I press it again it shows and it goes back by itself. 问题是,如果我再次按它显示它,它会自动返回。 Can anyone help me? 谁能帮我? Here is my script: 这是我的脚本:

$(document).ready(function(){

$('.menu-icon').click(function(){
    $('#navigator').animate({left:'0px'},200);
    $(this).animate({left:'250px'},200);
    $('.menu-icon').click(function(){
        >$('#navigator').animate({left:'-250px'},200);
        >$(this).animate({left:'0px'},200);
}); 
});
>});

You have placed a click handler inside a click handler so it will run multiple times. 您已在单击处理程序中放置了一个单击处理程序,因此它将多次运行。 Twice first time, then three times, then four times etc. 先是两次,然后是三次,然后是四次等。

You need to have a single handler and decide how to animate based on the current state of the element . 您需要有一个处理程序,并根据元素的当前状态决定如何设置动画。 eg something like the following (not tested): 例如以下内容(未经测试):

$(document).ready(function () {

    $('.menu-icon').click(function () {
        if ($('#navigator').css("left") != "0px") {
            $('#navigator').animate({
                left: '0px'
            }, 200);
            $(this).animate({
                left: '250px'
            }, 200);
        } else {
            $('#navigator').animate({
                left: '-250px'
            }, 200); > $(this).animate({
                left: '0px'
            }, 200);
        }
    });
});

I would suggest testing the "current state" using a class you toggle on the element as testing css values is notoriously unreliable during animation. 我建议使用你在元素上切换的类测试“当前状态”,因为测试css值在动画期间是众所周知的不可靠。

eg something like: 例如:

    if ($('#navigator').toggleClass("open").hasClass("open")) {

Here you are attaching the click event listener two times. 在这里,您将附加click事件侦听器两次。 One normal and one after clicking, thats why its happening use jquery toggle 一个正常,一个点击后,这就是为什么它发生使用jquery切换

or use in this way 或以这种方式使用

$(document).ready(function(){

   $('.menu-icon').click(function(){
     var navigator = $('#navigator');
     if(navigator.offset().left == 0)
     {
        navigator.animate({left:'-250px'},200);
        $(this).animate({left:'0px'},200);
     }
     else
     {
        navigator.animate({left:'0px'},200);
        $(this).animate({left:'250px'},200);
     }

  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM