gpt4 book ai didi

javascript - 是否有 Internet Explorer 认可的 selectionStart 和 selectionEnd 替代品?

转载 作者:行者123 更新时间:2023-12-03 08:23:51 25 4
gpt4 key购买 nike

找出在真实浏览器中选择的内容很简单:

var range = {
start: textbox.selectionStart,
end: textbox.selectionEnd
}

但是 IE 像往常一样不理解。执行此操作的最佳跨浏览器方法是什么?

最佳答案

我将再次发布此功能,因为这个问题与另一个问题相关联。

以下将在所有浏览器中完成这项工作,并在不严重影响性能的情况下处理所有新行问题。我是在 some toing and froing 之后到达这里的现在我非常确信这是最好的此类功能。

更新

这个函数假设 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(/\r\n/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);

关于javascript - 是否有 Internet Explorer 认可的 selectionStart 和 selectionEnd 替代品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/235411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com