使用箭头键时,满足于跳到另一个元素

时间:2017-11-27 12:14:19

标签: javascript html

如果contenteditable在文本末尾有span元素,并且当使用箭头键时,它会跳转到另一个满足。

例如;当我的光标到达并且光标跳到第三个contenteditable部分时,我正在第二个contenteditable上移动箭头键。但是光标必须留在第二部分。

<div class="container translationSectiontargetText" contenteditable="true" spellcheck="false" dir="ltr"  >
before
</div>

<div class="container translationSectiontargetText" contenteditable="true" spellcheck="false" dir="ltr"  ><span class="tag" data-number="1" contenteditable="false">1</span>target content<span class="tag" data-number="1" contenteditable="false">1</span></div>

<div class="container translationSectiontargetText" contenteditable="true" spellcheck="false" dir="ltr"  >
after
</div>

这是jsfiddle链接;

https://jsfiddle.net/7jf80nv8/

1 个答案:

答案 0 :(得分:0)

我希望它会对你有所帮助

&#13;
&#13;
let divs = document.querySelectorAll('div');
divs.forEach(div => {
	div.onkeydown= event => {
  	let position = document.getSelection().getRangeAt(0).startOffset;
    let first_span_text_length = div.querySelectorAll('span')[0].innerText.length;
  	let text_length = div.innerText.length - first_span_text_length - 1 
  	if(event.keyCode == 39 && position == text_length){
  		return false;
  	}
}
});
&#13;
<div class="container translationSectiontargetText" contenteditable="true" spellcheck="false" dir="ltr"  >
before
</div>

<div class="container translationSectiontargetText" contenteditable="true" spellcheck="false" dir="ltr"  ><span class="tag" data-number="1" contenteditable="false">1</span>target content<span class="tag" data-number="1" contenteditable="false">1</span></div>

<div class="container translationSectiontargetText" contenteditable="true" spellcheck="false" dir="ltr"  >
after
</div>
&#13;
&#13;
&#13;