Home Web Front-end JS Tutorial js obtains the coordinates of the input cursor of the specified control. Compatible with IE, Chrome, Firefox and other mainstream browsers_javascript skills

js obtains the coordinates of the input cursor of the specified control. Compatible with IE, Chrome, Firefox and other mainstream browsers_javascript skills

May 16, 2016 pm 05:33 PM
cursor coordinate

Upload the code directly
Copy the code The code is as follows:

var kingwolfofsky = {
/**
* Get the coordinates of the input cursor in the page
* @param {HTMLElement} input box element
* @return {Object} return 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 = ' ';
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(/n/g, '
').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];
},
// 获取光标在文本框的位置
_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";
}

------------------ -------------------------------------------------- -------------------------------------------------- ------------------
Call code:
Copy code The code is as follows:

var elem = document.getElementById(controlID);
var p = kingwolfofsky.getInputPositon(elem);
p.left;/ /Get the coordinates of the specified location
p.top;//Same as above
p.bottom;//Same as above
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Turn Easy T cursor movement between monitors on or off on Windows 11 Turn Easy T cursor movement between monitors on or off on Windows 11 Sep 30, 2023 pm 02:49 PM

Often, when using a dual monitor setup, the question arises of how to seamlessly move the cursor from one monitor to the other. It can be frustrating when your mouse cursor moves from one monitor to another without your control. Wouldn't it be great if Windows allowed you to easily switch from one monitor to another by default? Luckily, Windows 11 has a feature that does just that, and it doesn't require a lot of technical knowledge to perform it. What does easing cursor movement between monitors do? This feature helps prevent cursor drift when moving the mouse from one monitor to another. By default, this option is disabled. If you turn it on, the mouse

How to solve the problem of black screen and cursor when booting up Windows 7 How to solve the problem of black screen and cursor when booting up Windows 7 Dec 30, 2023 pm 10:25 PM

The Windows 7 system has currently stopped updating, so if there is a problem, you can only solve it yourself. As shown below, there are many situations where the cursor goes black after booting the computer, and you need to troubleshoot one by one. If you don’t want to spend time troubleshooting, you can just reinstall the system. What to do if there is only a black screen with a cursor when Windows 7 starts up? The first solution: Restart the computer, and immediately press and hold the "F8" button on the keyboard after restarting. Then select "Last Known Good Configuration" in the advanced system menu. The second solution: press the shortcut key "CTRL+SHIFT+ESC" to see if the task manager can be brought up. If so, right-click to end Explorer.exe in the process and then create a new run Explorer.exe to try.

How to set the cursor color of Debian 11 Xfce terminal? How to set the cursor color of Debian 11 Xfce terminal? Jan 03, 2024 pm 02:36 PM

What is Xfce? Xfce is a free software that runs on Unix-like operating systems (such as Linux, FreeBSD and Solaris) and provides a lightweight desktop environment. How to adjust the cursor color in Debian11Xfce terminal? Let’s take a look at the specific operations with the editor. Click [Edit]-[Preferences]. Switch to the [Color] tab. Check Customize [Cursor Color] and click the color selection button on the right. After opening the palette, click to select the cursor color you want to set.

What to do if there is no cursor when clicking on the input box What to do if there is no cursor when clicking on the input box Nov 24, 2023 am 09:44 AM

Solutions for clicking the input box without a cursor: 1. Confirm the focus of the input box; 2. Clear the browser cache; 3. Update the browser; 4. Use JavaScript; 5. Check the hardware device; 6. Check the input box properties; 7. Debug JavaScript code; 8. Check other elements of the page; 9. Consider browser compatibility.

How to solve Win10 red alert and black screen with only the mouse visible? What should I do if Win10 red alert turns up and the screen is black and only the cursor is visible? How to solve Win10 red alert and black screen with only the mouse visible? What should I do if Win10 red alert turns up and the screen is black and only the cursor is visible? Jul 08, 2023 pm 06:49 PM

Red Alert is a traditional strategy game. Recently, a customer said that when he was playing Red Alert, a black screen occurred. However, he could only see the mouse on the screen and could not continue to play the software if only the cursor was there. Okay, so what should I do if the Win10 red alert shows a black screen with only the cursor visible? The editor below will share with you the solution to the Win10 red alert black screen with only the mouse visible. How to solve the problem of Win10 red alert and black screen, only the computer mouse can be seen? 1. Find the document as shown below in the folder name. 2. Open the shortcut icon and add the "-win" identifier. 3. Click with the mouse to select the document as shown below, and select "Open as text document". 4. Modify the resolution as shown in the figure below.

What to do if linux vi does not display the cursor What to do if linux vi does not display the cursor Mar 22, 2023 am 09:39 AM

Solution to Linux vi not displaying the cursor: 1. Log in to the Linux system and enter the terminal; 2. Display the cursor by executing the "echo -e "\033[?25h"" method.

What key is used to switch the keypad area between editing functions and cursor control? What key is used to switch the keypad area between editing functions and cursor control? Jul 26, 2021 pm 02:44 PM

The key that enables the keypad area to switch between editing functions and cursor control is NumLock; Numlock refers to locking the numbers. If the Numlock key is canceled on the keyboard, the numbers on the keypad cannot be used.

Find all possible coordinates of a parallelogram in Java Find all possible coordinates of a parallelogram in Java Aug 26, 2023 pm 07:41 PM

A parallelogram is a quadrilateral with two pairs of parallel sides, where the opposite sides are of equal length and the diagonals are of equal measure. InthisarticlewearegoingtofindallpossiblecoordinatessofaParallelogram.Basically,wewillfindallthepossiblecoordinatesfromthegiventhreecoordinatestomakeaparallelogramofanon-zeroarea.Herethethreegivencoordinatesarenotfix

See all articles