将光标设置为contenteditable div的结尾 [英] Set cursor to the end of contenteditable div

查看:875
本文介绍了将光标设置为contenteditable div的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将光标设置为next / prev contenteditable标记的末尾,如果当前的标记为空,但是当我设置焦点时,它会将焦点添加到文本的开头而不是结束
几乎所有对SO的解决方案但似乎没有对我有用。这里是我正在尝试的简单代码

I am trying to set the cursor to the end of next/prev contenteditable tag if the current one is empty, but when I set focus it adds focus to the begining of the text and not end Tried almost all solution on SO but none seemed to work for me. Here the simple code I am trying

HTML CODE

<div id = 'main'>
<div id = 'n1' contenteditable=true> Content one</div>
<div id = 'n2' contenteditable=true> Content 2</div>
<div id = 'n3' contenteditable=true> Content 3</div>
<div id = 'n4' contenteditable=true> Content 4</div>

JS CODE

$('#main div').keydown(function(){
if(!$(this).text().trim()){
    $(this).prev().focus();
   //setCursorToEnd(this.prev())
    }
});


function setCursorToEnd(ele)
  {
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(ele, 1);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    ele.focus();
  }


推荐答案

您正在使用jQuery并获取来自jQuery的元素。您必须将其转换为本机DOM元素(通过jQuery-get函数)才能使用setCurserToEnd - 函数:

you are using jQuery and getting the element from jQuery. You must convert it into a native DOM element (via the jQuery-get Function) to use the "setCurserToEnd"-Function:

您的方法调用:

setCursorToEnd(this.prev());

工作解决方案:

setCursorToEnd($(this).prev().get(0));

查看更新的小提琴: http://jsfiddle.net/dvH5r/4/

这篇关于将光标设置为contenteditable div的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆