Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用javascript将光标移动到contenteditable表单中的父级?_Javascript_Html_Contenteditable - Fatal编程技术网

如何使用javascript将光标移动到contenteditable表单中的父级?

如何使用javascript将光标移动到contenteditable表单中的父级?,javascript,html,contenteditable,Javascript,Html,Contenteditable,这是我的尝试:它几乎可以工作,只是现在它将光标放在可编辑容器中的第一个跨距之前或之后,而不是光标所在的跨距 var div=document.querySelector('div'); div.onkeydown=固定光标; div.onclick=fixCursor; 函数fixCursor(){ //获取当前选择及其所在的节点 var selection=window.getSelection(); var container=selection.anchorNode; //如果它是文本节

这是我的尝试:它几乎可以工作,只是现在它将光标放在可编辑容器中的第一个跨距之前或之后,而不是光标所在的跨距

var div=document.querySelector('div');
div.onkeydown=固定光标;
div.onclick=fixCursor;
函数fixCursor(){
//获取当前选择及其所在的节点
var selection=window.getSelection();
var container=selection.anchorNode;
//如果它是文本节点,则改为获取它的父节点
if(selection.anchorNode.nodeType==3)
容器=selection.anchorNode.parentElement;
//如果不应编辑容器
if(container.classList.contains('noediting')){
console.log('无编辑',selection.anchorOffset)
//获取元素位置
var position=Array.from(div.childNodes).indexOf(container);
//将新位置设置为当前元素之前或之后
var newPosition=位置;
如果(selection.AnchoroOffset>0)
新位置=位置+1;
控制台日志(位置,新位置)
//创建/设置新选择(光标)
var cursor=document.createRange();
cursor.setStart(container.parentElement,newPosition);
cursor.collapse(true);
selection.removeAllRanges();
selection.addRange(光标);
}
}
divspan{
颜色:#888
}

我是普通文本没有人应该编辑我,但你可以编辑我
但不是我