如何在textarea中设置光标?它不适用于oninput事件。 [英] How to set cursor at end in textarea ? it doesn't work on oninput event.

查看:270
本文介绍了如何在textarea中设置光标?它不适用于oninput事件。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,当我在textarea中输入d时,它将d替换为文档然后我希望光标位于文本的末尾,但是它在第一个位置显示如何修复它?即时通讯使用ucbrowser 11.0浏览器。



我尝试过:



< html>



< body>



< textarea id =ta> < / textarea>



< / body>



< script>



函数replacetext()

{



var ta = document.getElementById(ta );



var a = ta.value.replace(d,document);



ta.value = a;



ta.selectionStart = ta.selectionEnd = ta.value.length;



}



< / script>



< / html>

解决方案

oninput 不是正确的选择,因为每次按键都会改变。

使用 onchange ,但是你必须验证字母' d ',它可能包含输入的任何单词。

您必须使用 / d / g 进行全球更换。



< pre lang =HTML> < html >
< body > ;

< textarea id = ta onchange = replacetext() > < / textarea >
< script >

function replacetext() {
var ta = document .getElementById( ta);
ta.value = ta.value.replace(/ d / g, document );
ta.selectionStart = ta.selectionEnd = ta.value.length;

}

< / script >
< < span class =code-leadattribute> / body >

< ; / html >
























函数replacetext()

{



var ta = document.getElementById(ta );



var replacement = ta.value.replace(/ d / g,document);



ta.value =;



ta.value =已更换;



ta .selectionStart = ta.selectionEnd = replacement.length;



}







here is my code when i type d in textarea it replaces "d" as "document" then i want the cursor at end of the text but it shows at 1st position how to fix it? i m using ucbrowser 11.0 browser.

What I have tried:

<html>

<body>

<textarea id="ta" ></textarea>

</body>

<script>

function replacetext()
{

var ta = document.getElementById("ta");

var a = ta.value.replace("d","document");

ta.value = a;

ta.selectionStart = ta.selectionEnd = ta.value.length;

}

</script>

</html>

解决方案

oninput is not a right choice since it will change for every key press.
use onchange instead , however you have to validate the letter 'd' which might contain in any word of the input.
you have to use /d/g for global replacement.

<html>
<body>

    <textarea id="ta" onchange="replacetext()"></textarea>
    <script>

        function replacetext() {
            var ta = document.getElementById("ta");
            ta.value = ta.value.replace(/d/g, "document"); 
            ta.selectionStart = ta.selectionEnd = ta.value.length;

        }

    </script>
</body>

</html>


after many tries i tried this code and its work perfect











function replacetext()
{

var ta = document.getElementById("ta");

var replaced = ta.value.replace(/d/g,"document");

ta.value = "";

ta.value = replaced;

ta.selectionStart=ta.selectionEnd=replaced.length;

}




这篇关于如何在textarea中设置光标?它不适用于oninput事件。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆