我有三个contenteditable
div,我想知道,用户通过Tab键或鼠标点击放置光标或插入符号的div,
<div contenteditable="true"></div>
<div contenteditable="true"></div>
<div contenteditable="true"></div>
有人可以帮帮我吗?
答案 0 :(得分:3)
我制定了一个更好的解决方案,这需要将要检查光标的所有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>
答案 1 :(得分:2)
使用document.activeElement
。这只是返回当前焦点在页面上的任何元素。 (MDN)
答案 2 :(得分:2)
使用onfocus事件,无论何时聚焦元素都会触发......
示例:
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:
<div contenteditable="true" id=1></div>
<div contenteditable="true" id=2></div>
<div contenteditable="true" id=3></div>
<input type="label" id="showRes"></input>