我可以在保持焦点的同时移动 DOMElement 吗?
假设我有一个带有 textarea
的简单 HTML 页面,并且我想将该 textarea
包装在 DIV 中。但是,这种情况并不总是发生在启动/页面加载时,因此用户可能会将焦点放在该区域,甚至正在打字。
我可以通过创建一个 DIV,将其附加到 textarea
的父级,然后将 textarea
放入其中来移动/包裹该区域,效果很好。但是,当我这样做时,焦点将从 textarea
中移除,如果用户正在打字,他们会生气。
如何在不中断用户的情况下移动 textarea
的 DOM 节点?这可能吗?
Suppose I have a simple HTML page with a textarea
, and I want to wrap that textarea
in a DIV. However, this doesn't always happen on startup / page load, so the user might have focus in that area, or even be typing.
I can move / wrap the area by creating a DIV, appending it to the textarea
's parent, then putting the textarea
inside of it, and it works great. However, when I do that, focus is removed from the textarea
and if the user was in the middle of typing, they're going to get angry.
How can I move the textarea
's DOM node without interrupting the user? Is this even possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据浏览器的不同,您也许可以使用 document.activeElement 确定哪个元素具有焦点。在执行移动之前保存值,然后使用文本区域中的 .focus() 将焦点设置回与您保存的元素相同的元素。
Depending on the browser you may be able to determine which element has focus by using document.activeElement. Save the value before performing the move and then afterwards set the focus back using .focus() in the textarea is the same element as what you saved.
好吧,重新聚焦(使用
focus()
)是一回事,但您还希望将用户的光标保持在同一位置(如果他做出了选择,也可能是他当前的选择)。不过,使用document.selection
/range
API 是可能的,请参阅 https://developer.mozilla.org/en/DOM/range 。此链接 描述了在 IE 中使用该 API 的解决方案(略有不同的问题)。
Well, refocusing (using
focus()
) is one thing, but you'll also want to keep the user's cursor at the same location (and possibly his current selection, if he's made one). It is possible though, using thedocument.selection
/range
API, see https://developer.mozilla.org/en/DOM/range .This link describes a solution (slightly different problem) using that API in IE.
您只需在移动所有内容后重置焦点即可。
使用。
移动后在您的文本区域上
You only have to reset the focus after you move everything.
Use
On your textArea after the move.
将文本区域附加到 div 后,您只需在文本区域上调用焦点即可,如 fiddle
< HTML
JAVASCRIPT
After appending the textarea to the div you simply have to call focus on the textarea, demonstrated in this fiddle
HTML
JAVASCRIPT