简体   繁体   English

手机的基本jQuery切换菜单不起作用

[英]Basic jquery toggle menu for mobile not working

I have a very basic toggle menu using jQuery's on: tap which isn't working: 我有一个使用jQuery的非常基本的切换菜单on: tap不起作用:

<nav id="mobile-nav">
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        etc...
    </ul>
</nav>

<div id="anchor">
    <header>
        <img src="menu-icon.png">
    </header>
</div>

Then, 然后,

$(document).ready(function() {
    var speed = "fast";

    $("#anchor").addClass("hidden");

    $("#anchor.hidden header img").on("tap", function() {
        $("#mobile-nav").animate({
            left: "0px"
        }, speed);

        $("header").animate({
            left: "252px"
        }, speed);

        $("#anchor").removeClass("hidden");
        $("#anchor").addClass("active");
    });

    $("#anchor.active header img").on("tap", function() {
        $("#mobile-nav").animate({
            left: "-252px"
        }, speed);

        $("header").animate({
            left: "0"
        }, speed);

        $("#anchor").removeClass("active");
        $("#anchor").addClass("hidden");
    });

});

#mobile-nav is a div which is 250px in width and is set to an absolute position with a left of -252px , which is then set to 0 when the image icon is tapped (making it slide into view). #mobile-nav是一个div, width250px ,设置为-252pxabsolute positionleft -252px ,然后点击图像图标时将其设置为0 (使其滑入视图)。 As you can see, once it slides out, it should remove the hidden class and add an active class. 如您所见,一旦滑出,它应该删除hidden类并添加一个active类。 Then I set a custom tap function to slide it back and remove the active class and add hidden again. 然后,我设置了一个自定义tap功能以将其向后滑动并删除active类并再次添加hidden It will slide out, but not slide back. 它将滑出,但不会向后滑。 What am I doing wrong? 我究竟做错了什么?

I think the issue is that you have multiple events triggered on your image click. 我认为问题在于图像点击触发了多个事件。 Try something like this: 尝试这样的事情:

$(document).ready(function() {
    var speed = "fast";

    $("#anchor").addClass("hidden");

    $("#anchor header img").on("click", function() {
        $('#anchor').hasClass('active') ? left = '-=252px' : left = '+=252px';
        $("#mobile-nav, header").animate({'left': left}, speed);    
        $("#anchor").toggleClass("hidden active");
    });

});

Fiddle 小提琴

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

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