最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery - If cursor position at the startend in a textfield - Stack Overflow

programmeradmin6浏览0评论

i have a textarea and I want to check if the cursor is at the start or at the end (I dont need the current position).
Did anybody know a simple jQuery solution?

Thanks in advance!
Peter

i have a textarea and I want to check if the cursor is at the start or at the end (I dont need the current position).
Did anybody know a simple jQuery solution?

Thanks in advance!
Peter

Share Improve this question edited Oct 11, 2010 at 8:35 Marko 72.2k29 gold badges125 silver badges160 bronze badges asked Oct 11, 2010 at 8:14 PeterPeter 11.9k31 gold badges101 silver badges155 bronze badges 3
  • Do you mean <input type="text"> or a <textarea>? – Tim Down Commented Oct 11, 2010 at 8:36
  • I mean <input type="text">. Is textbox the current word? – Peter Commented Oct 11, 2010 at 8:45
  • Guess so. I'm never certain what people mean. – Tim Down Commented Oct 11, 2010 at 9:05
Add a ment  | 

2 Answers 2

Reset to default 8

Assuming you mean a <input type="text"> rather than a textarea, here's a non-jQuery solution (that you can still use with your jQuery code). It will almost certainly be less code than a jQuery plug-in.

UPDATE 12 November 2011

Having said that, I have developed a jQuery plug-in for just his kind of task, and it is indeed bigger than the code below.

var textInput = document.getElementById("your_id"), val = textInput.value;
var isAtStart = false, isAtEnd = false;
if (typeof textInput.selectionStart == "number") {
    // Non-IE browsers
    isAtStart = (textInput.selectionStart == 0);
    isAtEnd = (textInput.selectionEnd == val.length);
} else if (document.selection && document.selection.createRange) {
    // IE <= 8 branch
    textInput.focus();
    var selRange = document.selection.createRange();
    var inputRange = textInput.createTextRange();
    var inputSelRange = inputRange.duplicate();
    inputSelRange.moveToBookmark(selRange.getBookmark());
    isAtStart = inputSelRange.pareEndPoints("StartToStart", inputRange) == 0;
    isAtEnd = inputSelRange.pareEndPoints("EndToEnd", inputRange) == 0;
}

alert("At start: " + isAtStart + ", at end: " + isAtEnd);

Yep, use this awesome jQuery plugin.

Need more info? Come back here with more questions :)

Update
The original blog post associated with the plugin is down.

Thanks to the Awesome Power of the wayback machine, you can still view it.

http://web.archive/web/20080620163228/http://blog.0xab.cd/jquery-plugin---fieldselection

God I love that website.

发布评论

评论列表(0)

  1. 暂无评论