<div class="test" contenteditable="true"></div>
function isItTheEnd()
{
//div内全部文本
var text = $('.test').text().trim();
//当前光标所在行:光标前文本长度
var this_leng = window.getSelection().focusOffset;
//当前光标所在行:行文本
var this_text = window.getSelection().getRangeAt(0).endContainer.data;
//当前光标所在行:下一个兄弟元素
var next_text = window.getSelection().getRangeAt(0).endContainer.nextSibling;
//兼容光标所在行为空时,文本中间空字符或空换行
var text_leng = 0;
if (this_text != undefined || (this_text == '' && next_text != null))
{
if (this_text == '' && next_text == null)
{
this_text = '';
this_leng = -1;
}
else
{
text_leng = this_text.length;
}
}
else if (this_text == null && next_text != null && $(next_text).get(0).tagName == 'DIV')
{
this_text = '';
this_leng = -1;
}
else
{
if (next_text == null || (next_text != null && next_text.nextSibling == null))
{
this_text = '';
text_leng = this_leng;
}
else
{
this_text = '';
this_leng = -1;
}
}
//当前行文本长度==光标前文本长度,且当前行文本是在所有文本的末尾
if (text_leng == this_leng && confirmEnding(text, this_text))
{
//光标在可编辑div的末尾处
}
}
//字符串最后位置
function confirmEnding(str, target)
{
// 请把你的代码写在这里
var start = str.length - target.length;
var arr = str.substr(start, target.length);
if (arr == target)
{
return true;
}
return false;
}
function isItTheStart()
{
//兼容文本框为空
if (this_text == undefined && text == '')
{
this_text = '';
}
if (this_text != undefined)
{
//光标前文本长度==0且当前行文本是总文本的起始文本
if (this_leng == 0 && confirmStarting(text, this_text))
{
//当前光标在div的开头位置
}
}
}
//字符串最前位置
function confirmStarting(str, target)
{
var arr = str.substr(0, target.length);
if (arr == target)
{
return true;
}
return false;
}
判断光标是否在可编辑div的末尾、开头处
于 2022-03-22 11:21:54 首次发布