我正在尝试创建一个模拟的聊天框,它需要在div的左侧和右侧弹出聊天。这些谈话中的每一个也都是div。我想不出如何将div附加到外部div的右侧。在我的代码中,我将一些文本附加到我想要添加到外部div的div中。如果可能的话,我想用香草Javascript来做这件事。
function pressEnter() {
if (event.keyCode === 13) {
event.preventDefault;
// get text
var text = document.getElementById("client_text_area").value;
// create new div
var newdiv = document.createElement('div');
newdiv.id = "human_chat"
// create text node to append
text = document.createTextNode(text);
newdiv.appendChild(text);
}发布于 2020-07-10 19:58:43
使用left: 0%将子元素放置在其父元素中,并拥抱其左侧。使用left: 50%将这个子程序的左侧放置在其父节点的中间。所以我们可以看到,left: 100%会把孩子的左边和它的父母的最右边的边缘放在一起。类似地,可以使用right: 100%将子节点定位到其父节点的左侧:
.parent {
position: absolute;
left: 50%; top: 50%;
width: 100px; height: 100px;
margin-left: -50px; margin-top: -50px;
background-color: #900;
}
.parent > .child {
position: absolute;
width: 50px; height: 50px;
top: 25px;
background-color: #090;
}
/* These are the rules that should interest you! */
.parent > .child.left { right: 100%; }
.parent > .child.right { left: 100%; }<div class="parent">
<div class="child left"></div>
<div class="child right"></div>
</div>
为了通过javascript设置这些值,您可以修改yourElem.style上的值。
例如,如果您希望newdiv坚持其父级的右侧,您可以这样做:
newdiv.style.position = 'absolute';
newdiv.style.left = '100%';发布于 2020-07-10 20:04:43
我会把这个放在Gershom回答下面的评论中,但是由于我还不能发表评论,所以我把它写在了一个答复中。
正如Gershom所共享的,使用CSS对div进行样式化。使用JavaScript创建类时,可以向div添加类,如下所示:
newdiv.classList.add('class-name');https://stackoverflow.com/questions/62841342
复制相似问题