简体   繁体   English

使用javascript传递可编辑的h2元素值以形成textarea

[英]Pass editable h2 element value to form textarea using javascript

I have an H2 element : <h2 contenteditable="true" class="input">This is a text</h2>我有一个H2 元素<h2 contenteditable="true" class="input">This is a text</h2>

And I have textarea element : <textarea class="output">This is another</textarea>我有textarea 元素<textarea class="output">This is another</textarea>

Now the H2 element is editable as you see and i want his content (what ever the user will type) to update the input element value live.现在H2 元素是可编辑的,如您所见,我希望他的内容(用户将输入的内容)实时更新输入元素值

How can i?我怎样才能? (using javascript) (使用javascript)

If you're using Jquery you could use the following jsfiddle如果您使用的是 Jquery,则可以使用以下 jsfiddle

jquery https://jsfiddle.net/kd9jLcs6/1/ jquery https://jsfiddle.net/kd9jLcs6/1/

Which uses the keyup function to update the h2's innertext with that of the text area它使用 keyup 函数将 h2 的内部文本更新为文本区域的内部文本

If you need pure JavaScript solution just use HTMLElement: input event which states:如果您需要纯JavaScript解决方案,只需使用HTMLElement: input 事件,其中规定:

The event also applies to elements with contenteditable enabled, and to any element when designMode is turned on.该事件还适用于启用了contenteditable元素,以及打开designMode时的任何元素。 In the case of contenteditable and designMode , the event target is the editing host.contenteditabledesignMode的情况下,事件目标是编辑主机。 If these properties apply to multiple elements, the editing host is the nearest ancestor element whose parent isn't editable.如果这些属性适用于多个元素,则编辑宿主是最近的父元素不可编辑的祖先元素。

As your h2 element has contenteditable attribute with the value true , it should work.由于您的h2元素具有值为true contenteditable属性,因此它应该可以工作。

Try the following:请尝试以下操作:

 const h2 = document.getElementsByClassName('input')[0]; const textarea = document.getElementsByClassName('output')[0]; h2.addEventListener('input', e => textarea.value = e.target.innerHTML);
 <h2 contenteditable="true" class="input">This is a text</h2> <textarea class="output">This is another</textarea>

I hope this helps!我希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM