简体   繁体   English

jQuery使用2个元素切换

[英]Jquery toggle using 2 elements

this is my script, I'm using a toggle so I can animate a sliding menu. 这是我的脚本,我使用了切换按钮,因此可以为滑动菜单设置动画。

    $("div.show-menu").click().toggle(
        function() {
            // first alternation
            $("#slideover").animate({
                right: "512px"
                }, 300);
            $(".menu-button").html('close menu');


        }, function() {
            // second alternation
            $("#slideover").animate({
                right: "0"
                }, 300);
            $(".menu-button").html('open menu');

    });

Though I really need the toggle to work using 2 elements on the page. 尽管我确实需要切换才能使用页面上的2个元素。 For example see below... 例如看下面...

<div class="show-menu one">open menu</div> // this is element one

<div class="show-menu two">open menu</div> // this is element two

I need it so, if element one get's click first, you can close the menu using element two on the first click. 我需要它,如果首先单击元素1,则可以在第一次单击时使用元素2关闭菜单。 What is happening now is that you have to click element two twice in order for it to close the menu - vice versa 现在发生的事情是您必须两次单击元素两次才能关闭菜单-反之亦然

I guess this is the toggle coming into play, any help would be great thanks. 我想这是拨动开关,任何帮助将非常感谢。

Cheers Josh 干杯乔希

$('.show-menu').on('click', function () {

    //check the state of the .menu-button, if it's closed then run the open animation, if it's open then run the close animation
    if ($(".menu-button").html() == 'close menu') {
        $("#slideover").animate({
            right: "0"
        }, 300);
        $(".menu-button").html('open menu');
    } else {
        $("#slideover").animate({
            right: "512px"
        }, 300);
        $(".menu-button").html('close menu');
    }
});

.on() is new in jQuery 1.7 and replaces .bind() in this instance, if you are using jQuery < 1.7 then use .bind() . .on()是jQuery 1.7中的新功能,在此实例中将替换.bind() ,如果您使用的是jQuery <1.7以下,请使用.bind()

What about 关于什么

$('.show-menu').on('click', function () {
    if ($("#slideover").css("right") == '512px') {
        $("#slideover").animate({
            right: "0"
        }, 300);
        $(".menu-button").html('open menu');

    } else {
        $("#slideover").animate({
            right: "512px"
        }, 300);
        $(".menu-button").html('close menu');
    }
});

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

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