Per*_*eus 21 javascript firefox textbox cursor
我需要一个代码来查找文本框/文本区域中光标的当前位置.它应该适用于chrome和firefox.以下是我使用的代码:
<!DOCTYPE html>
<html>
<head>
<script>
function textbox()
{
document.getElementById('Javascript_example').value = document.activeElement.id;
var ctl = document.getElementById('Javascript_example');
alert(ctl);
var startPos = ctl.selectionStart;
alert(startPos);
var endPos = ctl.selectionEnd;
alert(endPos);
}
</script>
</head>
<body>
<input id="Javascript_example" name="one" type="text" value="Javascript_example" onclick="textbox()">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
有什么建议吗?
Tim*_*own 42
除了ID属性中的空格(它无效)以及在检查选择之前替换输入值之外,它看起来还不错.
function textbox()
{
var ctl = document.getElementById('Javascript_example');
var startPos = ctl.selectionStart;
var endPos = ctl.selectionEnd;
alert(startPos + ", " + endPos);
}Run Code Online (Sandbox Code Playgroud)
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">Run Code Online (Sandbox Code Playgroud)
此外,如果您支持IE <= 8,则需要注意这些浏览器不支持selectionStart和selectionEnd.
这是一种可能的方法.
function isMouseInBox(e) {
var textbox = document.getElementById('textbox');
// Box position & sizes
var boxX = textbox.offsetLeft;
var boxY = textbox.offsetTop;
var boxWidth = textbox.offsetWidth;
var boxHeight = textbox.offsetHeight;
// Mouse position comes from the 'mousemove' event
var mouseX = e.pageX;
var mouseY = e.pageY;
if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
if(mouseY>=boxY && mouseY<=boxY+boxHeight){
// Mouse is in the box
return true;
}
}
}
document.addEventListener('mousemove', function(e){
isMouseInBox(e);
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
101308 次 |
| 最近记录: |