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

javascript - Get Textarea Cursor Position in AngularJs - Stack Overflow

programmeradmin3浏览0评论

This question boils down to needing to get the cursor position of a <textarea> element in a directive. In short, all I need to work in this.

var position = element.selectionStart;

There are at least 5 answers on the subject using various methods, e.g. this one for angular, this one for some jQuery extension, enter link description here.

I have read them all and decided to just try to get the selection start object. Here is my PLNKR. I have no idea what I am doing wrong. Note - the background change stuff is to see whether or not I am selecting the right element, which I am. Edit here is a snippet of the code that fails:

      link: function(scope, elem, attrs) {
          var textArea = elem.find("#itemTextArea");
          textArea.bind('click', function() {
              //This gets to undefined, even though selectionStart is a property of textarea*
              scope.testValue = elem.selectionStart;
          });
      },

*

P.S. Click on text area to immediately know what's happening in directive.

This question boils down to needing to get the cursor position of a <textarea> element in a directive. In short, all I need to work in this.

var position = element.selectionStart;

There are at least 5 answers on the subject using various methods, e.g. this one for angular, this one for some jQuery extension, enter link description here.

I have read them all and decided to just try to get the selection start object. Here is my PLNKR. I have no idea what I am doing wrong. Note - the background change stuff is to see whether or not I am selecting the right element, which I am. Edit here is a snippet of the code that fails:

      link: function(scope, elem, attrs) {
          var textArea = elem.find("#itemTextArea");
          textArea.bind('click', function() {
              //This gets to undefined, even though selectionStart is a property of textarea*
              scope.testValue = elem.selectionStart;
          });
      },

*https://developer.mozilla/en-US/docs/Mozilla/Tech/XUL/Property/selectionStart

P.S. Click on text area to immediately know what's happening in directive.

Share Improve this question edited Nov 21, 2022 at 8:15 sideshowbarker 88.2k29 gold badges215 silver badges211 bronze badges asked Jan 4, 2016 at 21:31 VSOVSO 12.6k28 gold badges115 silver badges200 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 13

The syntax you are looking for is:

scope.testValue = textArea.prop("selectionStart");

This also seems to work

scope.testValue = textArea[0].selectionStart;

发布评论

评论列表(0)

  1. 暂无评论