我有this FIDDLE

    <div class="sidebarmenu" style="position: absolute; left: -200000px">
         Show/hide div
    </div>
    <div class="image" style="position: absolute; left: -200000px">
        <img src="http://diymusician.cdbaby.com/wp-content/uploads/2012/07/Builder-of-the-House.jpg">
    </div>


单击时,将切换“ .sidebarmenu”。我希望“ .image”与div一起切换。我怎样才能做到这一点?

最佳答案

要定位多个元素,请用逗号,分隔每个元素

例如:$('.sidebarmenu, .image')

 $('#showmenu').click(function() {
        var hidden = $('.sidebarmenu').data('hidden');
        $('#showmenu').text(hidden ? 'Show Menu' : 'Hide Menu');
        if(hidden){
            $('.sidebarmenu, .image').css({
                position: 'absolute',
                left: -200000
            })
        } else {
            $('.sidebarmenu, .image').css({
                position: '',
                left: 0
            })
        }
        $('.sidebarmenu, .image').data("hidden", !hidden);

    });


DEMO

使用jQuery toggle()简化代码

$('.sidebarmenu, .image').toggle();

10-06 04:21