gpt4 book ai didi

javascript - 如何在 Internet Explorer 7 中使用 jQuery 获取文本区域中的选定文本?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:09:39 24 4
gpt4 key购买 nike

我尝试了 jquery-fieldselection plugin获取文本区域中的选定文本。

它在 Firefox 和 Chrome 中运行良好,但在 Internet Explorer 7 中运行不佳。

我像这样使用 getSelection() 方法:

textarea.getSelection();

当文本区域内的文本为 12345 并且所有这些文本都被选中时,Firefox 和 Chrome 返回:

start: 0    // Correct!
end: 5

当 Internet Explorer 7 返回时:

start: 5    // Why ??
end: 5

我正在寻找使用 jQuery 的跨浏览器解决方案。

最佳答案

只是看了一下 tthelibrary,它对 IE 的行为有所不同,因为它不支持现代浏览器支持的某些方法。可能是那里的代码不完美。

使用以下方法:

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
};
}

使用方法:

你需要textarea的dom对象..因此:

var textArea=    $("textarea")[0] or getElementbyId("textareaid");

var selectedText=getInputSelection(textArea);

var start=selectedText.start;
var end=selectedText.end;

Live Demo

关于javascript - 如何在 Internet Explorer 7 中使用 jQuery 获取文本区域中的选定文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7186586/

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