来自页面底部的动态div - Javascript

时间:2012-03-03 15:00:44

标签: javascript html

每次在我的数据库中找到新用户时,我想插入一个新的div。如果我更改CSS,我可以使用以下代码(从类中删除“bottom”和“absolute”)。问题是它从顶部开始,每个div都插入到前一个div之下。我希望div位于屏幕的左下角,然后在插入新div时向上移动。它本质上会推动现有的div,而最新的div将位于堆栈的底部。关于如何做到这一点的任何想法?任何帮助,将不胜感激。谢谢!

此代码将插入一个新div,但它只是放在前一个div之上。

.greyBox {
    padding:8px;
    background: grey;
    margin-bottom:8px;
    width:200px;
    height:50px;
    bottom:0;
    position:absolute;
}
.redBox {
    padding:8px;
    background: red;
    margin-bottom:8px;
    width:200px;
    height:25px;
    bottom:1;
    position:absolute;
}

<p>
  <button id="after">New User</button>
  <button id="reset">reset</button>
</p>

<div class="greyBox">Users</div>

$("#after").click(function () {
     $('.greyBox').after("<div class='redBox'>User 1</div>");
});

$("#reset").click(function () {
     location.reload();
});

http://jsfiddle.net/ymTtB/

2 个答案:

答案 0 :(得分:1)

添加一个类“bottom”的新div容器 http://jsfiddle.net/4np4q/

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>

<style type="text/css">
    .bottom{
    position: absolute;
    bottom: 0;     
    }
    .greyBox{
        padding:8px;
        background: grey;
        margin-bottom:8px;
        width:200px;
        height:50px;

    }

    .redBox{
        padding:8px;
        background: red;
        margin-bottom:8px;
        width:200px;
        height:25px;
    }
</style>

</head>
<body>

  <p>
  <button id="after">New User</button>
  <button id="reset">reset</button>
  </p>

  <div class="bottom">
    <div class="greyBox">Users</div>
</div>
<script type="text/javascript">

    $("#after").click(function () {
      $('.greyBox').after("<div class='redBox'>User 1</div>");
    });

    $("#reset").click(function () {
      location.reload();
    });

</script>
</body>
</html>

答案 1 :(得分:0)

这是position: absolute上的.redbox

.greyBox {
    padding:8px;
    background: grey;
    margin-bottom:8px;
    width:200px;
    bottom:0;
    position:absolute;
}

.redBox {
    padding:8px;
    background: red;
    margin-bottom:8px;
    width:200px;
    height:25px;
}

另外,我想你试图添加到.greyBox元素,而不是之后添加

$("#after").click(function () {
     $('.greyBox').append("<div class='redBox'>User 1</div>");
});

$("#reset").click(function () {
     $('.greyBox').children().remove();
});

http://jsfiddle.net/Bb6am/

如果您确实想要.after() greyBox,则需要使用包装并对其应用“底部”样式:

.users {
    width:200px;
    bottom:0;
    position:absolute;
}
.greyBox {
    padding:8px;
    background: grey;
    margin-bottom:8px;
}

<p>
  <button id="after">New User</button>
  <button id="reset">reset</button>
</p>

$("#after").click(function () {
     $('.greyBox').after("<div class='redBox'>User 1</div>");
});

$("#reset").click(function () {
     $('.users').children().not('.greyBox').remove();
});

http://jsfiddle.net/Bb6am/2/