javascript textarea cursor positioning method (compatible with IE and FF)_javascript skills
WBOY
Release: 2016-05-16 18:09:44
Original
1063 people have browsed it
Today I am working on a blog forwarding function, just like the function of Sina Weibo. There is a textArea, which is the box where we post our blogs. Other people's blogs have a forwarding button. When we click this forwarding button, His meager amount will enter the textArea. It seems to be a very simple text box assignment. In fact, the difficulty is that the cursor at this time is positioned at the front.
So I searched Baidu and Google and found the method below IE
var tea=document.getElementById("ID of text box"); var txt=textArea.createTextRange(); txt.moveEnd("character",0- tempText.text.length); txt.select();
But this method is only available under IE browser, so I found a blog through Internet search I googled for a long time and tried various methods. Most of them either did not support IE or IE ONLY. Finally, the master told me that an old page had this function. I found that code and tried it. It worked for both IE and FF! Share the code
function locatePoint(){ var aCtrl = document.getElementById("txtContent"); if (aCtrl.setSelectionRange) { setTimeout(function() { aCtrl.setSelectionRange(0, 0); // Position the cursor At the beginning of the textarea, if you need to position it to another location, please modify it yourself aCtrl.focus(); }, 0); }else if (aCtrl.createTextRange) { var textArea=document .getElementById("txtContent"); var tempText=textArea.createTextRange(); tempText.moveEnd("character",0-tempText.text.length); tempText.select(); } }
var tea=document.getElementById("ID of the text box"); tea.setSelectionRange(0, 0); // Position the cursor at the beginning of the textarea and need to locate it Please modify it yourself for other positions tea.focus();
So for the compatible method, we can use an if to add judgment. The integration method is as follows, just like in that post html part
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn