Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 跟随用户输入的元素_Javascript_Jquery_Html - Fatal编程技术网

Javascript 跟随用户输入的元素

Javascript 跟随用户输入的元素,javascript,jquery,html,Javascript,Jquery,Html,我创建了一个名为“bunny”的元素(image div),一个输入表单和一个字段集。我还有一个本地主机web服务器,它为我的聊天运行我的websocket服务器。我正在尝试实现一个函数,其中对于发送的每一条消息(跨越),bunny元素都放在每条消息的旁边 我在这样做时遇到的问题是: <div id="bunny"> </div> <input id="message" type="text" /> <button type="button" id="

我创建了一个名为“bunny”的元素(image div),一个输入表单和一个字段集。我还有一个本地主机web服务器,它为我的聊天运行我的websocket服务器。我正在尝试实现一个函数,其中对于发送的每一条消息(跨越),bunny元素都放在每条消息的旁边

我在这样做时遇到的问题是:

<div id="bunny">
</div>

<input id="message" type="text" />
<button type="button" id="movebunny">Bunny</button>

<fieldset id="showMsg" >
<!--messages are shown here-->
</fieldset>
  • 由于消息是span,所以bunny元素会复制自身并附加到每个span,而不仅仅是消息的末尾

  • bunny元素并不完全位于消息的旁边,它通常位于新行的跨度之下,我在JS中尝试了appendTo和InsertAfter

HTML:

<div id="bunny">
</div>

<input id="message" type="text" />
<button type="button" id="movebunny">Bunny</button>

<fieldset id="showMsg" >
<!--messages are shown here-->
</fieldset>
//js代码还有一点,但它们都只是为了连接到服务器//


如果您对点击按钮发送的每封邮件末尾的元素有任何建议,我们将不胜感激,谢谢

您确实需要显示更多的代码,或者创建一个JSFIDLE,但不需要额外的上下文:只需使用不同的框架(注意,字段集并不真实地描述其中的内容。字段集用于表单字段。您正在使用它包装惰性消息):

然后使用CSS确保兔子在正确的位置

div.messages { position: relative; }
.from.listener { float: left; position: relative; }
.from.sender { float: right; position: relative; }
.bunny { width: ...; height: ...; background: url('bunny.png'); }
.from.listener .bunny { position: absolute; left: 0}
.from.sender .bunny { position: absolute; right: 0}
.hidden { display: none!important; }
在出现任何消息之前,将兔子元素一直放在顶部:

<div class="messages">
  <div class="message">
    <div class="from sender">bob</div>
    <div class="body">blahblahblah</div<
  </div>
  <div class="message">
    <div class="from listener">carol</div>
    <div class="body">blahblahblah</div<
  </div>
  ...
</div>
<div class="hidden bunny">^_^</div>
从一开始就有一个持久的引用,然后每次构建新消息时

var newmsg = ....;
bunny.classList.remove("hidden");
newmsg.appendChild(bunny);
messages.appendChild(newmsg);

完成后,
appendChild
在页面上移动元素(因为DOM元素不能同时存在于两个位置,因此页上元素的appendChild只需将其移动到新位置即可)。

了解您的意思了吗?因为文本描述不太清楚,所以请看一下这两个:&您能在显示一些消息后显示生成的HTML吗?还有CSS?我只是想谢谢你,还没有尝试过,但它是有意义的。谢谢你!
var bunny = document.querySelector(".bunny");
var newmsg = ....;
bunny.classList.remove("hidden");
newmsg.appendChild(bunny);
messages.appendChild(newmsg);