0

我有这个输入框,它接受输入,文本被附加在一个<div>称为“父”的内部,作为另一个<div>称为“子”。

编码:

const send = () => {
  const parent = document.querySelector('.parent');
  const text = document.querySelector('.text').value;
  const newtext = document.createElement("div");
  newtext.classList.add(".child");
  newtext.innerHTML = "Me: " + text;
  parent.appendChild(newtext);
}
* {
  margin: 0;
  padding: 0;
}

body {
  position: absolute;
}

.parent {
  position: relative;
  width: 100%;
}

.child {
  position: relative;
  height: fit-content;
  width: fit-content;
  text-align: right;
  max-width: 50%;
  white-space: pre-line;
  word-wrap: break-word;
}
<html>

<body>
  <input type="text" class="text">
  <button onclick="send()">Send</button>
  <div class="parent"></div>
</body>

</html>

我想让<div>“孩子”类出现在右侧。但是标签的未知宽度使得它很难与leftCSS 中的属性对齐。每次发布新文本时如何将其显示在右侧?

4

3 回答 3

1

您可以使用float: right(并且clear: both; 为了始终将其放置 在上一个条目下方)

顺便说一句:我也会用display: inline-block它来让它像它的内容一样窄,并删除那些“适合内容”的设置。

于 2021-06-19T12:02:56.330 回答
0

function send () {
  var text = document.getElementsByClassName("text")[0].value;
  document.getElementsByClassName("parent")[0].innerHTML = text;
}
<html>
<head>
<style>

html, body{
margin: 0;
padding: 0;
}

.parent{
  width: 50%;
  float: right;
}

.child{
  width: 50%;
}

</style>
</head>

<body>

<input type="text" class="text">
<button onclick="send()">Send</button>
<div class="parent"></div>

</body>
</html>

于 2021-06-19T12:11:38.827 回答
0

父级的宽度设置为 100% - 100% 什么?在给定的结构中,它是身体的 100%。body 没有给出明确的宽度,因此它占用了其中的宽度,即输入元素。

此外,在添加到 classList 时有一个错字,点不应该出现在 .child 上。

所以,这是一个问题,你希望父母的宽度在任何时候是多少?在这个片段中,没有做任何事情来改变现在的(固有)宽度,但孩子位于右侧,即它与提交按钮的末尾对齐。

如果您想让父级填充整个视口,则将主体设置为 100vw。

const send = () => {
    const parent=document.querySelector('.parent');
    const text=document.querySelector('.text').value;
    const newtext = document.createElement("div");
    newtext.classList.add("child");
    newtext.innerHTML = "Me: "+text;
    parent.appendChild(newtext);
    }
*{
    margin: 0;
    padding: 0;
    }
    body{
    position: absolute;
    rwidth: 100vw;
    }
    .parent{
    position: relative;
    width: 100%;
    }
    .child{
    position: relative;
    height: fit-content;
    width: fit-content;
    text-align: right;
    max-width: 50%;
    white-space: pre-line;
    word-wrap: break-word;
    left: 100%;
    transform: translateX(-100%);
    }
<html>
    <body>
    <input type="text" class="text">
    <button onclick="send()">Send</button>
    <div class="parent"></div>
    </body>
    </html>

于 2021-06-19T12:26:25.080 回答