JQuery animate .css(),而不是使用.animate()

JQuery animate .css() rather then using .anmiate()?

本文关键字:animate css JQuery      更新时间:2023-09-26

我想用动画的方式改变一个div的margin-top。

通常我会这样写:

 $("#mydiv").animate({ marginTop: '+='+myvar}, 200);

但这总是增加(或减少)值。我想要一种方法来简单地动画改变的值。

例如:如果div开始时的外边距为100,myvar值为50,我想对div进行动画,使其缩小到50。同样,如果myvar的值是200,我想让这个变化变成200。

我可以实现这一点,但重置CSS,例如:

$("#mydiv").css("margin-top", "0px");
$("#mydiv").animate({ marginTop: '+='+myvar}, 200);

,但这使得它有点笨拙。

有人知道可以实现这一点吗?

(Ps:不使用CSS转场)

编辑:在 下面添加我的代码
$("#info1tab").click(function() {
  $(".textbox").slideUp('200');
  $("#info1").delay(300).slideDown('200');
  var itemheight = $("#info1").css("height");
  var itemheightint = parseInt(itemheight);
  $("#photobox").animate({ marginTop: itemheightint }, 200);
});
$("#info2tab").click(function() {
  $(".textbox").slideUp('200');
  $("#info2").delay(300).slideDown('200');
  var itemheight = $("#info2").css("height");
  var itemheightint = parseInt(itemheight);
  $("#photobox").animate({ marginTop: itemheightint }, 200);
});

$('#mydiv').animate({marginTop: myvar});有什么问题?

http://jsfiddle.net/muVsE/

创建具有所需CSS属性的其他CSS类,然后执行:

$("#mydiv").addClass("classname", 1000);

$("#mydiv").removeClass("classname", 1000);

试试下面的代码:

$("#mydiv").css("margin-top", "0px");
$("#mydiv").animate({ marginTop: topMargin+myvar}, 200);

希望这对JSFiddle有帮助

$('#left-bg, #right-bg').click(
    function(){
        $(this).animate({'width': '100%'},600).siblings().animate({'width':'0'},600);
    });

或者你可以使用这个jsfield

$('#left-bg, #right-bg').click(
    function(){
        $(this).animate({'width': '100%'},600).siblings().animate({'width':'0'},600);
        $('<button class="show">Show all</button>')
            .appendTo('#wrapper');
    });
    $('.show').live('click',
                    function(){
                        $('#left-bg').animate(
                            {
                                'width': '50%'
                            },600);
                        $('#right-bg').animate(
                            {
                                'width': '50%'
                            },600);
                        $(this).remove();
                    });

或者你可以用它来展开一个div同时缩小另一个div:

$('.cell')
    .on('mouseenter', function(){
        $(this).animate ({width:"75%"},"slow").siblings('.cell').animate({'width': '15%'}, "slow");
    })
    .on('mouseleave', function(){
        $(this).add($(this).siblings('.cell')).animate ({width:"45%"},"slow");
    });

问候。