【问题标题】:jQuery: Animate Margins to Auto?jQuery:动画边距自动?
【发布时间】:2011-05-29 12:04:51
【问题描述】:

我正在尝试为图像设置动画,使其居中。这是我想使用的代码:

$('#myImage').animate({'margin-right': 'auto'});

但是当我这样做时,它会被忽略并且不会改变边距。
有没有办法让边缘自动设置动画,或者以其他方式居中图像?

谢谢!

【问题讨论】:

    标签: javascript jquery css jquery-animate center


    【解决方案1】:

    因为 'auto' 不是数字,所以 jQuery 无法对其进行动画处理。

    如果您可以将图像从文档流中取出,您可以将位置设置为绝对或固定并尝试:

    $('#myImage').animate({'left': '50%', 'margin-left': -$('#myImage').width()/2 });
    

    【讨论】:

    • 如果你也想动画垂直居中,复制这条线,用顶部替换左边,用高度替换宽度。
    【解决方案2】:

    您不能为auto 属性设置动画。要将元素正确设置到屏幕中心,您需要将其定位为absolutely(或其他),然后计算屏幕大小、元素大小和滚动位置。这是类似的another SO answerHere is the Fiddle

    jQuery.fn.center = function () {
        this.css("position","absolute");
        var top = ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px",
            left = ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px";
        this.animate({top: top, left: left});
        return this;
    }
    

    或者,如果您只想要水平对齐,您可以从动画函数中删除顶部。如果您真的想获得创意,您可以删除position:absolute,并在动画后重新定位margin:auto,以防屏幕调整大小。 See another fiddle.

    jQuery.fn.center = function () {
        this.css("position","absolute");
        var left = ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px";
        this.animate({left: left}, function(){
            $(this).css({position: 'static', margin: '0 auto'});
        });
        return this;
    }
    $('#selector').center();
    

    【讨论】:

      【解决方案3】:

      扩展 Josiah Ruddell 的回答。如果你们需要您的图像以保持其在文档中的流动,请使用此修改后的 Josiah 答案版本。我的图像最初定位在margin: 0 -1000px,然后左右滑入计算出的边距。始终保持其在 dom 中的流动

      jQuery.fn.center = function () {
        var margin = ( $(window).width() - this.width() ) / 2;
        this.animate({
          marginLeft: margin, 
          marginRight: margin
        }, function(){
          $(this).css({margin: '0 auto'});
        });
        return this;
      } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-25
        • 2016-05-28
        • 1970-01-01
        • 2011-11-09
        • 1970-01-01
        • 2012-06-09
        • 2011-09-24
        相关资源
        最近更新 更多