[英]Cursor position/index on textarea onClick event in IE11
場景:用戶在文本區域上單擊(在內容之間的某個位置,只需單擊即可選擇任何字符)。 使用javascript需要找到光標的位置。 我們有以下腳本:
comp.focus();
var range = document.selection.createRange();
range.text='|';
var oldval = comp.value;
var pos= oldval.index('|');
代碼在IE <11上運行。 在IE 11中,“ dcoument.selection”未定義。 然后使用IE11的文檔說“ document.selection”應該是“ document.getSelection”。 因此嘗試了以下方法:
comp.focus();
var range = document.getSelection().createRange();
在ver11中,“ document.getSelection()。createRange()”顯示錯誤:對象不支持屬性或方法“ createRange()”。 然后嘗試獲取“ var sel = document.getSelection()”的對象。 當我嘗試打印為警報“ sel”時,它說“無法在undefiend或null引用上獲取toString屬性” 1.使用舊版本的document.selection.createRange效果很好,即使沒有任何字符被高亮顯示。 但是使用IE11並非如此。 2.如果沒有任何選定的字符,請讓我知道如何createRange evne。 需要解決方案/建議以繼續進行。
我使用此函數來獲取光標位置:
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
})(jQuery);
以下代碼返回光標位置:
comp.getCursorPosition();
與IE11搭配正常
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.