是否有Internet Explorer批准的selectionStart和selectionEnd替代品?

是否有Internet Explorer批准的selectionStart和selectionEnd替代品?,第1张

是否有Internet Explorer批准的selectionStart和selectionEnd替代品

我将再次发布此函数,以查看该问题是否与另一个问题相关联。

以下将在所有浏览器中完成工作,并处理所有新行问题,而不会严重影响性能。我经过一番折腾之后才来到这里,现在我很确信这是最好的功能。

更新

此函数确实假定textarea / input具有焦点,因此您可能需要在调用textarea的

focus()
方法之前先对其进行调用。

function getInputSelection(el) {    var start = 0, end = 0, normalizedValue, range,        textInputRange, len, endRange;    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {        start = el.selectionStart;        end = el.selectionEnd;    } else {        range = document.selection.createRange();        if (range && range.parentElement() == el) { len = el.value.length; normalizedValue = el.value.replace(/rn/g, "n"); // Create a working TextRange that lives only in the input textInputRange = el.createTextRange(); textInputRange.moveToBookmark(range.getBookmark()); // Check if the start and end of the selection are at the very end // of the input, since moveStart/moveEnd doesn't return what we want // in those cases endRange = el.createTextRange(); endRange.collapse(false); if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {     start = end = len; } else {     start = -textInputRange.moveStart("character", -len);     start += normalizedValue.slice(0, start).split("n").length - 1;     if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {         end = len;     } else {         end = -textInputRange.moveEnd("character", -len);         end += normalizedValue.slice(0, end).split("n").length - 1;     } }        }    }    return {        start: start,        end: end    };}var el = document.getElementById("your_input");el.focus();var sel = getInputSelection(el);alert(sel.start + ", " + sel.end);


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5148732.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存