我正在爲crossbrowser輸入寫一個擴展& textarea選擇getter和setter。 所以這是我寫我的代碼的方式:IE7中的HTMLInputElement
HTMLInputElement.prototype.getSelectionRange = get_selection_range;
HTMLInputElement.prototype.setSelection = set_selection_range;
HTMLTextAreaElement.prototype.getSelectionRange = get_selection_range;
HTMLTextAreaElement.prototype.setSelection = set_selection_range;
get_selection_range和set_selection_range是這些擴展功能。所以,我只是想取代
someInputElement.selectionStart = a; // and whole lot of code due to browser
someInputElement.selectionEnd = b; // compatibility
只有
someInputElement.setSelection(a, b);
someInputElement.setSelection({ start: a, end: b });
someOtherElement.setSelection(someInputElement.getSelection());
但後來我遇到了幾個困難IE7。首先,IE7不知道什麼是HTMLInputElement。
我不想擴展整個對象。那麼,這將是我會做的最後一件事,但我想逃避它。 函數get_selection_range和set_selection_range沒問題,不要問什麼,你已經看過幾次了。
所以問題是:是否有任何合法的替代IE中的JS的HTMLInputElement?
UPD:我做了我自己的解決方案,無需任何擴展全局對象類型:
var SmartInputSelection = Base.extend({
constructor: function (options) {
this.node = options.node;
this.CHARACTER = "character";
this.END_TO_END = "EndToEnd";
this.END_TO_START = "EndToStart";
},
setSelection: function (a, b) {
if (b === undefined && typeof a == "number")
b = a;
else if (b === undefined) {
b = a.end;
a = a.start;
}
if (this.node.selectionStart !== undefined) {
this.node.selectionStart = a;
this.node.selectionEnd = b;
} else {
var textRange = this.node.createTextRange();
textRange.collapse(true);
textRange.moveStart(this.CHARACTER, a);
textRange.moveEnd(this.CHARACTER, b - a);
textRange.select();
}
},
getSelection: function() {
var start, end;
if (this.node.selectionStart !== undefined) {
start = this.node.selectionStart;
end = this.node.selectionEnd;
} else {
var range = document.selection.createRange();
if (range == null) {
start = end = 0;
}
var textRange = this.node.createTextRange(),
duplicate = textRange.duplicate();
textRange.moveToBookmark(range.getBookmark());
duplicate.setEndPoint(this.END_TO_END, textRange);
end = duplicate.text.length;
duplicate.setEndPoint(this.END_TO_START, textRange);
start = duplicate.text.length;
}
return {
start: start,
end: end
};
}
});
所以現在我只是要聲明是這樣的:
function SelectSomeTextInsideInput (input /* input is some DOM element */) {
var smartInputSelection = new SmartInputSelection({ node: input });
smartInputSelection.setSelection(0);
smartInputSelection.setSelection(2, 5);
smartInputSelection.setSelection({ start: 2, end: 5 });
smartInputSelection.getSelection(); // start: 2, end: 5
}
是的,這是某種答案。雖然,如果我是CMI,我不會給你賞金=) –