使用jQuery来切换marginLeft?

时间:2014-04-27 21:40:16

标签: jquery

我有一个100%宽度的菜单,然后我检查宽度并将其从屏幕上甩掉。我想要达到的是切换marginLeft效果。

我有这个,显然不会重新插入。我在他们工作。

    var em = $(window).width() / parseFloat($("body").css("font-size"));
    emEm = em+'em'; //change px to em and add em unit i.e. XXem

    $('nav').width(emEm); //makes nav full width in em's
    $('nav').css('margin-left','-'+emEm); //throws nav off screen

    $('.menu').click(function() {
        $('nav').animate({
            marginLeft: '0' //bring nav back on screen
        }, 300);
    });

有没有办法切换菜单点击功能?

由于

3 个答案:

答案 0 :(得分:2)

分别做-100%0

http://jsfiddle.net/DerekL/5xrGu/

$('nav').animate({
    marginLeft: '-100%'
}, 300);

答案 1 :(得分:0)

编辑了这篇文章。看这个。我知道它可以更快更短,但现在这将有效。

<script>
    var clicked = false,
        margin_value;

    $('#on-click-id').click(function(){
        $('nav').stop(); //Stop the animation on each click
        if(clicked == false){
            margin_value = '+=10px';
            //Set clicked to true so the next click will be decreasing the margin
            clicked == true;
        } else if (clicked == false){
            margin_value = '-=10px';
            //Set clicked to false so the next click will be increasing the margin
            clicked = false;
        }

        $('nav').animate({
            marginLeft: margin_value //bring nav back on screen
        }, 300);
    })
</script>

答案 2 :(得分:0)

$('.menu').click(function() {
$('nav').toggle(function() {
$('nav').animate({marginLeft: "0"}, 300},
function() {
$('nav').animate({marginLeft: "100%"}, 300});