Jquery在父div

时间:2017-05-30 17:45:03

标签: jquery

我正在尝试动态添加div,并尝试将其定位为其父div的中心,但单击添加按钮时没有任何反应。

这是我的小代码

if ($('#dvChild').length==0)
{

        var parent = $('.parent');
    //var parentDimensions = parent.height() * parent.width();

    var child = $('.child');
    //var childDimensions = child.height() * child.width();

    var $divChild = $("<div>", {id: "dvChild"});
        $divChild.css({top: parent.height()/2 - child.height()/2 , left: parent.width()/2 -         child.width()/2 }) 
        $("#dvParent").append($divChild);
}

在jsfiddle https://jsfiddle.net/tridip/kzym5mu9/1/

中找到完整代码 请告诉我我犯了哪个错误。感谢

3 个答案:

答案 0 :(得分:1)

这是一种更简单的方法来获得你需要的东西:

https://jsfiddle.net/kzym5mu9/4/

$("#btnadd").click(function () {
    $('#dvParent').append('<div class="child">child</div>');
});

$('#btnDel').click(function(){
    $('.child').remove();
})

.child {
    height: 50%;
    width: 50%;
    background-color:yellow;
    position: absolute;
    top: 25%;
    left: 25%;
}

答案 1 :(得分:0)

按照以下方式更改CSS和jQuery

$("#btnadd").click(function () {
    if ($('#dvChild').length==0)
    {
    	var divChild = "<div id='dvChild'></div>";
		$("#dvParent").append(divChild);
    }
});
$("#btnDel").click(function () {
   $("#dvChild").remove();

});
.parent { 
  width: 200px;
  height: 200px; 
  background-color:red;
  position: relative;
}

#dvChild {
    height: 100px;
    width: 100px;
    background-color:yellow;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div id="dvParent" class="parent">parent div</div>
<br>
<button id="btnadd">Add Div</button>
<button id="btnDel">Remove Div</button>

答案 2 :(得分:0)

仅使用CSS就可以实现这一点:

<div style="width:400px; height:400px; display:table-cell; background-color:#f00; vertical-align: middle; text-align: center;">
<div style="display:inline-block;">asdasdsafsasfd</div>
</div>

在父母身上;添加"display;table-cell;vertical-align: middle;text-align: center;"

关于孩子;添加"display:inline-block;"

相关问题