最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Animate toggle margin-left of div using jQuery? - Stack Overflow

programmeradmin6浏览0评论

I've been trying to mimic others' code but with no luck. How can I get Div1 to toggle margin-left:30% when DivButton is clicked? Thank you.

/

HTML

<div id="Div1"></div>
<br><br>
<div id="DivButton"></div>

CSS

#Div1{
    background:blue;
    width:50%;
    height:50px;
    margin-left:0%;
}

#DivButton{
    background:green;
    width:20px;
    height:20px;
}

JS

$('#DivButton').click(function(){                

});


/* 
var toggleWidth = $("#Div1").width() == 365 ? "98%" : "365px"; 
$('#Div1').animate( {'width': toggleWidth}, 300, resize); 
*/

/* 
var toggleMargin = $("#Div1").marginLeft() == 30% ? "10%" : "30%"; 
$('#Div1').animate( {'margin-left': toggleMargin}, 300, resize); 
*/

I've been trying to mimic others' code but with no luck. How can I get Div1 to toggle margin-left:30% when DivButton is clicked? Thank you.

http://jsfiddle/3nc62rec/

HTML

<div id="Div1"></div>
<br><br>
<div id="DivButton"></div>

CSS

#Div1{
    background:blue;
    width:50%;
    height:50px;
    margin-left:0%;
}

#DivButton{
    background:green;
    width:20px;
    height:20px;
}

JS

$('#DivButton').click(function(){                

});


/* 
var toggleWidth = $("#Div1").width() == 365 ? "98%" : "365px"; 
$('#Div1').animate( {'width': toggleWidth}, 300, resize); 
*/

/* 
var toggleMargin = $("#Div1").marginLeft() == 30% ? "10%" : "30%"; 
$('#Div1').animate( {'margin-left': toggleMargin}, 300, resize); 
*/
Share Improve this question asked May 15, 2015 at 0:29 SherriSherri 3172 gold badges6 silver badges14 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3
var $div1 = $('#Div1')
$('#DivButton').click(function() {
  $div1.toggleClass('isOut')
  var isOut = $div1.hasClass('isOut')
  $div1.animate({marginLeft: isOut ? '30%' : '0'}, 300)
})

http://jsfiddle/3nc62rec/2/

You can use a jquery animation.

  $('#DivButton').animate({marginleft: "30%"}, 500);

Try this:

$('#DivButton').click(function () {
    $("#Div1").animate({
        marginLeft: '30%'
    }, 500);
});

JSFiddle Demo

发布评论

评论列表(0)

  1. 暂无评论