gpt4 book ai didi

javascript - 在 DOM 上移动输入时将光标保持在 html 输入中

转载 作者:行者123 更新时间:2023-12-03 11:56:15 24 4
gpt4 key购买 nike

当我在 DOM 上移动元素时,是否有任何简单的方法可以将光标保留在输入元素中?

示例:http://jsfiddle.net/y1nu1q4f/1/

<form>
<input type='text' name='a' /> ho ho ho
<input type='text' name='b' /> merry christmas
</form>
<script>
setTimeout(function(){
$('input[name="a"]').appendTo($('form'));
$('input[name="b"]').appendTo($('form'));
}, 3000);
</script>

此示例在 3 秒后移动文本输入。当输入获得焦点(光标位于内部)时,移动时它会失去焦点。是否可以将光标保留/返回到原始位置?

在我的应用程序中,我有很多输入,其 DOM 正在像这样重新组织,所以我需要一些简单而灵活的解决方案,而不是为每个输入放置一堆额外的属性和代码。 jQuery 解决方案优于纯 JavaScript。

提前感谢您的回答。

最佳答案

像这样的事情应该可以解决问题。

setTimeout(function(){
var focusedElement = jQuery(':focus'); // ideally specify tag, class or ID here before the ':focus' to avoid jQuery scanning all elements on the page.

$('input[name="a"]').appendTo($('form'));
$('input[name="b"]').appendTo($('form'));

if (focusedElement && focusedElement.length) { //fixed var name here
focusedElement.focus();
}
}, 3000);

关于javascript - 在 DOM 上移动输入时将光标保持在 html 输入中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25607648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com