判断光标是否在可编辑div的末尾、开头处


<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;
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值