在DOM中移动输入时,将光标保持在html输入中

时间:2014-09-01 14:09:06

标签: javascript jquery html dom

当我跨DOM移动元素时,有没有简单的方法将光标保持在input元素中?

示例: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更受欢迎。

提前感谢您的回答。

2 个答案:

答案 0 :(得分:1)

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

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);

答案 1 :(得分:0)

您可以使用focus()关注元素。

如果我以你的jsfiddle为例,你只需在切换后在函数中添加$('input').focus();。而且你很高兴。

所以:

setTimeout(function(){
   $('input').appendTo($('form'));
   $('input').focus();
}, 3000};

DEMO