Howto Place cursor at beginning of textarea

怎甘沉沦 提交于 2019-12-03 12:40:58

问题


I've found a couple resources for how to place the cursor in a textarea at the end of the text, but I can't sort out a simple way to make it appear at the beginning.

I'm prepopulating the textarea with some text and just want to make it easier on the users.


回答1:


Pass a reference to your textarea to this JS function.

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



回答2:


Depending on your needs, a simpler Javascript version is:

document.querySelector("textarea").focus(); //set the focus - cursor at end
document.querySelector("textarea").setSelectionRange(0,0); // place cursor at start

You can't just string them together either, to get rid of the double querySelector - not sure why.




回答3:


Removed the spaces between the tags
like this:

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


来源:https://stackoverflow.com/questions/1336585/howto-place-cursor-at-beginning-of-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!