jquery 将一个 div 缩放到其父 div 的中心

标签 jquery css jquery-animate

我在使用 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);
    });
}

fiddle :https://jsfiddle.net/84x55e07/4/

最佳答案

您可以使用 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/

关于jquery 将一个 div 缩放到其父 div 的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28497920/

相关文章:

javascript - Tiktok.com 和 Youtube shorts 如何自动滚动播放视频(在移动设备上)? react Javascript

css - 如何使 LESS hat 库 mixin 全局可用

javascript - 我的 div 使用 show() 正确淡入,但在动画完成后它会跳起来

javascript - jQuery - 动画 + 滚动顶部

javascript - jQuery animation() - 完成触发太快

jquery - 使用 jQuery 更改 HTML 标记?

javascript - jquery克隆选择框5次

jquery - 使用 Jquery 删除下一个所有包括 ($this) 的内容

javascript - 使用 jquery 重新选择所有复选框会导致奇怪的操作

html - 较大的字体大小在右对齐文本中向右移动