How to alternate Range moveStart in Firefox?

QUESTION

Does anybody know how to use range.setStart in the same way as range.moveStart works in IE? I'd like to implement backspace/delete in JS, something like this:

range.moveStart('character',-1); range.deleteContents();

but in Firefox

ANSWER

Firefox, along with all modern browsers except IE <= 8 uses DOM Ranges. There's no direct analogue to the moveStart method of IE's TextRange and it's tricky to do in the general case. If the range is within a text node and not at the start, it's easy; otherwise you'll need to walk backwards in the document to find the preceding text node and move the range into it. The following only works within a single text node:

function backspace(){
   
var sel = window.getSelection();

   
// If there is a selection rather than a caret, just delete the selection
   
if(!sel.isCollapsed){
        sel
.deleteFromDocument();
   
}elseif(sel.rangeCount){
       
var range = sel.getRangeAt(0);
       
if(range.startContainer.nodeType ==3&& range.startOffset >0){
            range
.setStart(range.startContainer, range.startOffset -1);
            sel
.removeAllRanges();
            sel
.addRange(range);
            sel
.deleteFromDocument();
       
}
   
}
}

WebKit and Firefox 4 have the modify method of Selection objects which solves the problem completely:

function backspace2(){
   
var sel = window.getSelection();

   
// If there is a selection rather than a caret, just delete the selection
   
if(!sel.isCollapsed){
        sel
.deleteFromDocument();
   
}elseif(sel.rangeCount && sel.modify){
        sel
.modify("extend","backward","character");
        sel
.deleteFromDocument();
   
}
}

转载于:https://www.cnblogs.com/yingzi/archive/2012/05/25/2518258.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值