[英]How to get the div in which the cursor or caret is placed?
I have three contenteditable
divs and I want to know ,in which div the user has placed the cursor or caret through tab key or mouse click, 我有三个
contenteditable
div,我想知道,用户通过Tab键或鼠标单击将光标或插入符号放在了哪个div中,
<div contenteditable="true"></div>
<div contenteditable="true"></div>
<div contenteditable="true"></div>
Can somebody help me out? 有人可以帮我吗?
I worked out a better solution ,this will need enclosing all the div
tags that you want to check for the cursor into a parent div
tag and using the document.getSelection()
object we can get the id of the div in which the cursor or caret is placed 我制定了一个更好的解决方案,这需要将要检查光标的所有
div
标签封装到父div
标签中,并使用document.getSelection()
对象获取光标所在的div的ID。插入符放置
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id=parent>
<div contenteditable="true" id=1>dddd
</div>
<div contenteditable="true" id=2>dddd
</div>
<div contenteditable="true" id=3>dddd
</div>
</div>
<input type="label" id="showRes"></input>
</body>
<script type="text/javascript">
var div = document.getElementsByTagName('div');
var out=document.getElementById('parent');
function findCursor(){
var x=document.getSelection();
var r=x.getRangeAt(0);
var tempnode=document.createElement("div");
tempnode.setAttribute("id","cursorhook");
r.surroundContents(tempnode);
document.getElementById('showRes').value=tempnode.parentNode.id;
document.getElementById(tempnode.parentNode.id).removeChild(document.getElementById("cursorhook"));
}
out.onkeyup=findCursor;
out.onclick=findCursor;
</script>
</html>
Use onfocus event which triggers whenever you are focussing an element ... 使用onfocus事件,该事件会在您聚焦某个元素时触发...
Example: 例:
var div = document.getElementsByTagName('div');
for(var i=0;i<div.length;i++)
div[i].addEventListener('focus',function(){document.getElementById('showRes').value = this.id;},false);
HTML : HTML:
<div contenteditable="true" id=1></div>
<div contenteditable="true" id=2></div>
<div contenteditable="true" id=3></div>
<input type="label" id="showRes"></input>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.