Javascript 如何将光标放置在文本区域的开头

Javascript 如何将光标放置在文本区域的开头,javascript,prototype,textarea,Javascript,Prototype,Textarea,我已经找到了一些关于如何将光标放置在文本末尾的文本区域的参考资料,但我无法找到一种简单的方法使光标显示在开头 我正在用一些文本预填充textarea,只是想让它对用户更方便 将对textarea的引用传递到此JS函数 function resetCursor(txtElement) { if (txtElement.setSelectionRange) { txtElement.focus(); txtElement.setSelectionRang

我已经找到了一些关于如何将光标放置在文本末尾的文本区域的参考资料,但我无法找到一种简单的方法使光标显示在开头


我正在用一些文本预填充textarea,只是想让它对用户更方便

将对textarea的引用传递到此JS函数

function resetCursor(txtElement) { 
    if (txtElement.setSelectionRange) { 
        txtElement.focus(); 
        txtElement.setSelectionRange(0, 0); 
    } else if (txtElement.createTextRange) { 
        var range = txtElement.createTextRange();  
        range.moveStart('character', 0); 
        range.select(); 
    } 
}

删除标签之间的空格,如下所示:

<textarea rows="5" cols="50" name="extra"></textarea>

根据您的需要,更简单的Javascript版本是:

document.querySelector("textarea").focus(); //set the focus - cursor at end
document.querySelector("textarea").setSelectionRange(0,0); // place cursor at start
您也不能仅仅将它们串在一起,以摆脱双查询选择器-不知道为什么。

jQuery方式:

$('textarea[name="mytextarea"]').focus().setSelectionRange(0,0);

请在使用
$(textareaSelector).val(val)

$(textareaSelector)[0].setSelectionRange(0, 0);
$(textareaSelector).focus();