[英]How do I get normal attributes of an element when selected with jQuery?
I have a textarea which I select using jQuery, and I want to find the position of the cursor within it. 我有一个textarea,我使用jQuery选择,我想找到它内的光标的位置。 I've found that in normal JavaScript you can do it with .selectionStart
, but doing $("#maintext").selectionStart
results in undefined
. 我发现,在正常的JavaScript你可以做到这一点.selectionStart
,但这样做$("#maintext").selectionStart
结果undefined
。
How can I do it? 我该怎么做?
selectionStart
is native DOM property so try this: selectionStart
是本机DOM属性,所以试试这个:
var selStart = $('#maintext').get(0).selectionStart;
The reason for this happening is that $('#maintext')
returns an array of jQuery wrapped DOM objects and in order to invoke a native method you need to get the underlying element. 发生这种情况的原因是$('#maintext')
返回一个jQuery包装的DOM对象数组,为了调用本机方法,你需要获取底层元素。
In that situation there might be a case for simply doing: 在这种情况下,可能只是做一个案例:
document.getElementById("maintext").selectionStart
and not have the overhead of creating a new jQuery object. 并且没有创建新jQuery对象的开销。
In jQuery 1.6, you could use prop()
. 在jQuery 1.6中,您可以使用prop()
。 In older versions, attr()
could be used. 在旧版本中,可以使用attr()
。
$("#maintext").prop("selectionStart");
However, selectionStart
and selectionEnd
properties are not supported in IE < 9. I've published a cross-browser function to work round this in a few places on Stack Overflow (for example, here ), or you could use my jQuery plug-in for dealing with textarea/text input selections. 但是,IE <9中不支持selectionStart
和selectionEnd
属性。我已经发布了一个跨浏览器函数,可以在Stack Overflow上的一些地方(例如, 这里 )使用它,或者你可以使用我的jQuery插件用于处理textarea /文本输入选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.