【问题标题】:jquery scale a div to the center of its parent divjquery 将 div 缩放到其父 div 的中心
【发布时间】:2015-02-13 10:52:12
【问题描述】:

我在使用 jquery 中的 .animate 功能将 div 向自己的中心缩放时遇到问题。我有一个 div(宽度和高度在单独的 css 文件中定义 - 46px 和 50px,位置设置为绝对)。这个 div 位于另一个 div(其父级)中,一个 52px * 52px 大小的正方形。我想要实现的是将子 div 缩放到它自己的中心(它有一个背景图像),但到目前为止它只缩放到父方形 div 的左上角。任何建议将不胜感激。

我现在有这个,

var PARENT_SQUARE_WIDTH = 52;
var PARENT_SQUARE_HEIGHT = 52;
var H = 56;
var W = 52;

function anim(childDiv) {
    $(childDiv).animate({
        height: H * 0.1 + "px",
        width: W * 0.1 + "px",
        left: "+=" + ((PARENT_SQUARE_WIDTH * 0.5) - (childDiv * 0.5)) + "px",
        top: "+=" + ((PARENT_SQUARE_HEIGHT * 0.5) - (childDiv * 0.5)) + "px"

    }, 600, "linear", function () {
        anim(childDiv);
    });
}

小提琴:https://jsfiddle.net/84x55e07/4/

【问题讨论】:

    标签: jquery css jquery-animate


    【解决方案1】:

    您可以使用left:50%top:%50 并将margin-top 设置为子本身的负半宽度,对margin-left 执行相同操作

    javascript

    var PARENT_SQUARE_WIDTH = 52;
    var PARENT_SQUARE_HEIGHT = 52;
    var H = 56;
    var W = 52;
    var childDiv = $("#childDiv");
    
    function anim(childDiv) {
        $(childDiv).animate({
            height: H * 0.1 + "px",
            width: W * 0.1 + "px",
            marginLeft: -(W * 0.1 / 2) + "px",
            marginTop: -(H * 0.1 / 2)  + "px"
    
        }, 600, "linear");
    }
    
    anim(childDiv);
    

    CSS

    #parentDiv{
        margin:50px auto;
        display:block;
        width:52px;
        height:52px;
        background: #99D100;
        position:relative;
    }
    
    #childDiv {
        position: absolute;
        background-image: url("http://exmoorpet.com/wp-content/uploads/2012/08/cat.png");
        width: 46px;
        height: 50px;
        top:50%;
        left:50%;
        margin-top: -25px;
        margin-left:-23px;
        background-size: 55%;
        background-position: center center;
        background-repeat: no-repeat;
    }
    

    https://jsfiddle.net/f0hn050a/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 2013-01-28
      • 1970-01-01
      相关资源
      最近更新 更多