我正在尝试创建一个消息传递页面,但是包含已发送消息的 div 堆叠在一起——每个“行”中有两个,而本应只有一个。
类为.message的div应该全部向右浮动,每行只有一个div。
我在我的元素中使用 jQuery。
#mydiv{
width: 80%;
margin: auto;
min-height: 100px;
max-height: 80%;
overflow-y: auto;
border: 3px solid red;
}
.message{
float: right;
width: 40%;
border: 2px solid aqua;
}
#messagebox{
position: absolute;
right: 11%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<div id="mydiv">
</div>
<p/>
<textarea id="messagebox" placeholder="Press enter to send message">
</textarea>
<script>
$('#messagebox').keypress(function(e){
if(e.which==13){
e.preventDefault();
send($(this).val());
$(this).val("");
}
});
function send(msg){
var msgDiv = "<div class='message'>"+msg+"</div>"
$('#mydiv').append(msgDiv);
}
</script>
</body>
</html>
最佳答案
您将需要使用 clear: both
来防止 .message
div 任一侧的任何 float 元素(或者您可以只使用 clear: left
以防止任何 float 元素出现在 .message
div 的左侧)。查看documentation .
#mydiv{
width: 80%;
margin: auto;
min-height: 100px;
max-height: 80%;
overflow-y: auto;
border: 3px solid red;
}
.message{
float: right;
width: 40%;
clear: both;/*prevents floating elements on both sides*/
border: 2px solid aqua;
}
#messagebox{
position: absolute;
right: 11%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<div id="mydiv">
</div>
<p/>
<textarea id="messagebox" placeholder="Press enter to send message">
</textarea>
<script>
$('#messagebox').keypress(function(e){
if(e.which==13){
e.preventDefault();
send($(this).val());
$(this).val("");
}
});
function send(msg){
var msgDiv = "<div class='message'>"+msg+"</div>"
$('#mydiv').append(msgDiv);
}
</script>
</body>
</html>
关于jquery - Div 不会右对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51523788/