动态添加div元素不会水平显示到具有特定宽度值的容器div元素中,始终分成新行。
这是我的代码
var i=1;
$(document).ready(function () {
$("#add").click(function(){
$('#container').append(
$('<div/>')
.addClass("dDiv")
.text("(hello world "+i+")")
);
i++;
});
})
&#13;
#main{
float:right;
width:500px;
border: 1px solid;
overflow:hidden;
white-space: nowrap;
display: block;
}
.dDiv{
display: inline-block;
float:right;
background-color:#ff0000;
margin:2px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="add">Add</div>
<div id="chat" style="float:right">
<div id="main">
<div id="container" style="float:right;">
</div>
</div>
</div>
&#13;
答案 0 :(得分:1)
只需删除float: right
的{{1}}声明即可。诀窍是all floated elements will automatically be declared as block level elements。如果您不想强制换行(因此溢出),则必须将它们视为内联或内联块级元素。
要强制.dDiv
遵守其内联块状态,只需不要为其指定浮点属性。
.dDiv
&#13;
var i=1;
$(document).ready(function () {
$("#add").click(function(){
$('#container').prepend(
$('<div/>')
.addClass("dDiv")
.text("(hello world "+i+")")
);
i++;
});
});
&#13;
#chat {
float: right;
}
#main{
width:500px;
border: 1px solid;
overflow: hidden;
}
#container {
overflow:hidden;
white-space: nowrap;
text-align: right;
}
.dDiv{
background-color:#ff0000;
display: inline-block;
margin:2px;
}
&#13;
答案 1 :(得分:0)
以下是您需要进行的更改:
#main {
text-align: right;
direction: rtl;
/* white-space: no-wrap; /* take this out */
}
.dDiv {
/* float: right /* take this out */
}
结果:
var i=1;
$(document).ready(function () {
$("#add").click(function(){
$('#container').append(
$('<div/>')
.addClass("dDiv")
.text("(hello world "+i+")")
);
i++;
});
})
&#13;
#main{
float:right;
direction:rtl;
text-align: right;
width:500px;
border: 1px solid;
overflow:hidden;
display: block;
}
.dDiv{
display: inline-block;
background-color:#ff0000;
margin:2px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="add">Add</div>
<div id="chat" style="float:right">
<div id="main">
<div id="container" style="float:right;">
</div>
</div>
</div>
&#13;
答案 2 :(得分:-1)
1)删除float:right
2)在#main div
上设置direction:rtl
3)您可能想要将overflow:auto
设置为#main div以便查看其他dDiv
var i = 1;
$(document).ready(function() {
$("#add").click(function() {
$('#container').append(
$('<div/>')
.addClass("dDiv")
.text("(hello world " + i + ")")
);
i++;
});
})
&#13;
#main {
width: 500px;
border: 1px solid;
overflow: hidden;
white-space: nowrap;
display: block;
direction: rtl;
}
.dDiv {
display: inline-block;
background-color: #ff0000;
margin: 2px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="add">Add</div>
<div id="chat" style="float:right">
<div id="main">
<div id="container" style="float:right;">
</div>
</div>
</div>
&#13;