在 Firefox 中,使用上面的脚本(包括在下面的内联),您可以通过单击字符串中间并键入,或使用键盘后退键(和 ctrl+左箭头)随时编辑文本区域的内容.
在IE中,光标总是跳到末尾。为什么会这样,我该如何预防?
HTML:
<textarea id="bob" name="bob">Some textarea content</textarea>
<div id="debug"></div>
JS:
$(document).ready(function(){
$("#bob").keyup(function(){
$("#bob").val($("#bob").val().substring(0,160));
$("#debug").append("\n+");
});
});
最佳答案
而不是使用 substring()
chop $("#bob")每次,只有当文本长度大于160时才这样做:
$(document).ready(function(){
var oldtext = $("#bob").val();
$("#bob").keyup(function(){
if( $("#bob").val().length > 160 )
$("#bob").val(oldtext);
else
oldtext = $("#bob").val();
$("#debug").append("\n+");
});
});
在 IE 中,每当 <textarea>
被修改,光标会跳转到末尾。
关于javascript - 为什么IE 8让这个JS的光标跳到textarea的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6899047/