js獲得指定控件輸入光標(biāo)的坐標(biāo)兼容IE,Chrome,火狐等多種主流瀏覽器
更新時間:2013年05月21日 15:17:43 作者:
js獲得指定控件光標(biāo)的坐標(biāo),兼容IE,Chrome,火狐等多種主流瀏覽器,實現(xiàn)代碼及調(diào)用代碼如下,感興趣的朋友可以參考下哈,希望對你有所幫助
直接上代碼
var kingwolfofsky = {
/**
* 獲取輸入光標(biāo)在頁面中的坐標(biāo)
* @param {HTMLElement} 輸入框元素
* @return {Object} 返回left和top,bottom
*/
getInputPositon: function (elem) {
if (document.selection) { //IE Support
elem.focus();
var Sel = document.selection.createRange();
return {
left: Sel.boundingLeft,
top: Sel.boundingTop,
bottom: Sel.boundingTop + Sel.boundingHeight
};
} else {
var that = this;
var cloneDiv = '{$clone_div}', cloneLeft = '{$cloneLeft}', cloneFocus = '{$cloneFocus}', cloneRight = '{$cloneRight}';
var none = '<span style="white-space:pre-wrap;"> </span>';
var div = elem[cloneDiv] || document.createElement('div'), focus = elem[cloneFocus] || document.createElement('span');
var text = elem[cloneLeft] || document.createElement('span');
var offset = that._offset(elem), index = this._getFocus(elem), focusOffset = { left: 0, top: 0 };
if (!elem[cloneDiv]) {
elem[cloneDiv] = div, elem[cloneFocus] = focus;
elem[cloneLeft] = text;
div.appendChild(text);
div.appendChild(focus);
document.body.appendChild(div);
focus.innerHTML = '|';
focus.style.cssText = 'display:inline-block;width:0px;overflow:hidden;z-index:-100;word-wrap:break-word;word-break:break-all;';
div.className = this._cloneStyle(elem);
div.style.cssText = 'visibility:hidden;display:inline-block;position:absolute;z-index:-100;word-wrap:break-word;word-break:break-all;overflow:hidden;';
};
div.style.left = this._offset(elem).left + "px";
div.style.top = this._offset(elem).top + "px";
var strTmp = elem.value.substring(0, index).replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br/>').replace(/\s/g, none);
text.innerHTML = strTmp;
focus.style.display = 'inline-block';
try { focusOffset = this._offset(focus); } catch (e) { };
focus.style.display = 'none';
return {
left: focusOffset.left,
top: focusOffset.top,
bottom: focusOffset.bottom
};
}
},
// 克隆元素樣式并返回類
_cloneStyle: function (elem, cache) {
if (!cache && elem['${cloneName}']) return elem['${cloneName}'];
var className, name, rstyle = /^(number|string)$/;
var rname = /^(content|outline|outlineWidth)$/; //Opera: content; IE8:outline && outlineWidth
var cssText = [], sStyle = elem.style;
for (name in sStyle) {
if (!rname.test(name)) {
val = this._getStyle(elem, name);
if (val !== '' && rstyle.test(typeof val)) { // Firefox 4
name = name.replace(/([A-Z])/g, "-$1").toLowerCase();
cssText.push(name);
cssText.push(':');
cssText.push(val);
cssText.push(';');
};
};
};
cssText = cssText.join('');
elem['${cloneName}'] = className = 'clone' + (new Date).getTime();
this._addHeadStyle('.' + className + '{' + cssText + '}');
return className;
},
// 向頁頭插入樣式
_addHeadStyle: function (content) {
var style = this._style[document];
if (!style) {
style = this._style[document] = document.createElement('style');
document.getElementsByTagName('head')[0].appendChild(style);
};
style.styleSheet && (style.styleSheet.cssText += content) || style.appendChild(document.createTextNode(content));
},
_style: {},
// 獲取最終樣式
_getStyle: 'getComputedStyle' in window ? function (elem, name) {
return getComputedStyle(elem, null)[name];
} : function (elem, name) {
return elem.currentStyle[name];
},
// 獲取光標(biāo)在文本框的位置
_getFocus: function (elem) {
var index = 0;
if (document.selection) {// IE Support
elem.focus();
var Sel = document.selection.createRange();
if (elem.nodeName === 'TEXTAREA') {//textarea
var Sel2 = Sel.duplicate();
Sel2.moveToElementText(elem);
var index = -1;
while (Sel2.inRange(Sel)) {
Sel2.moveStart('character');
index++;
};
}
else if (elem.nodeName === 'INPUT') {// input
Sel.moveStart('character', -elem.value.length);
index = Sel.text.length;
}
}
else if (elem.selectionStart || elem.selectionStart == '0') { // Firefox support
index = elem.selectionStart;
}
return (index);
},
// 獲取元素在頁面中位置
_offset: function (elem) {
var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement;
var clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0;
var top = box.top + (self.pageYOffset || docElem.scrollTop) - clientTop, left = box.left + (self.pageXOffset || docElem.scrollLeft) - clientLeft;
return {
left: left,
top: top,
right: left + box.width,
bottom: top + box.height
};
}
};
function getPosition(ctrl) {
var p = kingwolfofsky.getInputPositon(ctrl);
document.getElementById('show').style.left = p.left + "px";
document.getElementById('show').style.top = p.bottom + "px";
}
----------------------------------------------------------------------------------------------------------------------------------------
調(diào)用代碼:
var elem = document.getElementById(控件ID);
var p = kingwolfofsky.getInputPositon(elem);
p.left;//獲得指定位置坐標(biāo)
p.top;//同上
p.bottom;//同上
復(fù)制代碼 代碼如下:
var kingwolfofsky = {
/**
* 獲取輸入光標(biāo)在頁面中的坐標(biāo)
* @param {HTMLElement} 輸入框元素
* @return {Object} 返回left和top,bottom
*/
getInputPositon: function (elem) {
if (document.selection) { //IE Support
elem.focus();
var Sel = document.selection.createRange();
return {
left: Sel.boundingLeft,
top: Sel.boundingTop,
bottom: Sel.boundingTop + Sel.boundingHeight
};
} else {
var that = this;
var cloneDiv = '{$clone_div}', cloneLeft = '{$cloneLeft}', cloneFocus = '{$cloneFocus}', cloneRight = '{$cloneRight}';
var none = '<span style="white-space:pre-wrap;"> </span>';
var div = elem[cloneDiv] || document.createElement('div'), focus = elem[cloneFocus] || document.createElement('span');
var text = elem[cloneLeft] || document.createElement('span');
var offset = that._offset(elem), index = this._getFocus(elem), focusOffset = { left: 0, top: 0 };
if (!elem[cloneDiv]) {
elem[cloneDiv] = div, elem[cloneFocus] = focus;
elem[cloneLeft] = text;
div.appendChild(text);
div.appendChild(focus);
document.body.appendChild(div);
focus.innerHTML = '|';
focus.style.cssText = 'display:inline-block;width:0px;overflow:hidden;z-index:-100;word-wrap:break-word;word-break:break-all;';
div.className = this._cloneStyle(elem);
div.style.cssText = 'visibility:hidden;display:inline-block;position:absolute;z-index:-100;word-wrap:break-word;word-break:break-all;overflow:hidden;';
};
div.style.left = this._offset(elem).left + "px";
div.style.top = this._offset(elem).top + "px";
var strTmp = elem.value.substring(0, index).replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br/>').replace(/\s/g, none);
text.innerHTML = strTmp;
focus.style.display = 'inline-block';
try { focusOffset = this._offset(focus); } catch (e) { };
focus.style.display = 'none';
return {
left: focusOffset.left,
top: focusOffset.top,
bottom: focusOffset.bottom
};
}
},
// 克隆元素樣式并返回類
_cloneStyle: function (elem, cache) {
if (!cache && elem['${cloneName}']) return elem['${cloneName}'];
var className, name, rstyle = /^(number|string)$/;
var rname = /^(content|outline|outlineWidth)$/; //Opera: content; IE8:outline && outlineWidth
var cssText = [], sStyle = elem.style;
for (name in sStyle) {
if (!rname.test(name)) {
val = this._getStyle(elem, name);
if (val !== '' && rstyle.test(typeof val)) { // Firefox 4
name = name.replace(/([A-Z])/g, "-$1").toLowerCase();
cssText.push(name);
cssText.push(':');
cssText.push(val);
cssText.push(';');
};
};
};
cssText = cssText.join('');
elem['${cloneName}'] = className = 'clone' + (new Date).getTime();
this._addHeadStyle('.' + className + '{' + cssText + '}');
return className;
},
// 向頁頭插入樣式
_addHeadStyle: function (content) {
var style = this._style[document];
if (!style) {
style = this._style[document] = document.createElement('style');
document.getElementsByTagName('head')[0].appendChild(style);
};
style.styleSheet && (style.styleSheet.cssText += content) || style.appendChild(document.createTextNode(content));
},
_style: {},
// 獲取最終樣式
_getStyle: 'getComputedStyle' in window ? function (elem, name) {
return getComputedStyle(elem, null)[name];
} : function (elem, name) {
return elem.currentStyle[name];
},
// 獲取光標(biāo)在文本框的位置
_getFocus: function (elem) {
var index = 0;
if (document.selection) {// IE Support
elem.focus();
var Sel = document.selection.createRange();
if (elem.nodeName === 'TEXTAREA') {//textarea
var Sel2 = Sel.duplicate();
Sel2.moveToElementText(elem);
var index = -1;
while (Sel2.inRange(Sel)) {
Sel2.moveStart('character');
index++;
};
}
else if (elem.nodeName === 'INPUT') {// input
Sel.moveStart('character', -elem.value.length);
index = Sel.text.length;
}
}
else if (elem.selectionStart || elem.selectionStart == '0') { // Firefox support
index = elem.selectionStart;
}
return (index);
},
// 獲取元素在頁面中位置
_offset: function (elem) {
var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement;
var clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0;
var top = box.top + (self.pageYOffset || docElem.scrollTop) - clientTop, left = box.left + (self.pageXOffset || docElem.scrollLeft) - clientLeft;
return {
left: left,
top: top,
right: left + box.width,
bottom: top + box.height
};
}
};
function getPosition(ctrl) {
var p = kingwolfofsky.getInputPositon(ctrl);
document.getElementById('show').style.left = p.left + "px";
document.getElementById('show').style.top = p.bottom + "px";
}
----------------------------------------------------------------------------------------------------------------------------------------
調(diào)用代碼:
復(fù)制代碼 代碼如下:
var elem = document.getElementById(控件ID);
var p = kingwolfofsky.getInputPositon(elem);
p.left;//獲得指定位置坐標(biāo)
p.top;//同上
p.bottom;//同上
您可能感興趣的文章:
- IE、FF、Chrome瀏覽器中的JS差異介紹
- C++獲取多瀏覽器上網(wǎng)歷史記錄示例代碼(支持獲取IE/Chrome/FireFox)
- 在firefox和Chrome下關(guān)閉瀏覽器窗口無效的解決方法
- flex chrome瀏覽器調(diào)試出現(xiàn)空白的解決方法
- javascript判斷chrome瀏覽器的方法
- js代碼判斷瀏覽器種類IE、FF、Opera、Safari、chrome及版本
- ZeroClipboard插件實現(xiàn)多瀏覽器復(fù)制功能(支持firefox、chrome、ie6)
- 如何實現(xiàn)chrome瀏覽器關(guān)閉頁面時彈出“確定要離開此面嗎?”
- chrome瀏覽器當(dāng)表單自動填充時如何去除瀏覽器自動添加的默認(rèn)樣式
相關(guān)文章
JavaScript實現(xiàn)獲取網(wǎng)絡(luò)通信進(jìn)度
這篇文章主要為大家詳細(xì)介紹了如何使用Fetch?API和XMLHttpRequest(XHR)來執(zhí)行網(wǎng)絡(luò)請求,并重點說明如何獲取這兩種方法的網(wǎng)絡(luò)請求進(jìn)度,感興趣的可以了解下2023-12-12解決火狐瀏覽器下JS setTimeout函數(shù)不兼容失效不執(zhí)行的方法
今天檢查自己用JQuery+AJAX+PHP做的網(wǎng)站后臺登錄檢測,愛其他瀏覽器中兼容性還不錯 結(jié)果到了火狐(FireFox)瀏覽器下setTimeout這個JS內(nèi)置函數(shù)不執(zhí)行了,本文將提供詳細(xì)的解決方法2012-11-11JavaScript原始數(shù)據(jù)類型Symbol的用法詳解
Symbol是ES6中引入的一種新的基本數(shù)據(jù)類型,用于表示一個獨一無二的值。它是JavaScript中的第七種數(shù)據(jù)類型。本文將詳細(xì)講講Symbol的使用,需要的可以參考一下2022-11-11JS使用setInterval計時器實現(xiàn)挑戰(zhàn)10秒
這篇文章主要為大家詳細(xì)介紹了JS使用setInterval計時器實現(xiàn)挑戰(zhàn)10秒,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-11-11JavaScript實現(xiàn)數(shù)字?jǐn)?shù)組按照倒序排列的方法
這篇文章主要介紹了JavaScript實現(xiàn)數(shù)字?jǐn)?shù)組按照倒序排列的方法,涉及javascript中sort方法的使用技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04