不工作方法Selection.removeRange()

时间:2014-11-28 15:09:29

标签: javascript

HTML:

<p>
    <span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui aliquam quod aperiam veniam animi. Debitis iure sit incidunt sint dicta enim voluptatum inventore itaque cumque error. Neque voluptatem beatae fuga?</span>
    <span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui aliquam quod aperiam veniam animi. Debitis iure sit incidunt sint dicta enim voluptatum inventore itaque cumque error. Neque voluptatem beatae fuga?</span>
</p>

<button>Remove range</button>

JavaScript的:

var p = document.body.firstElementChild;

var rng, selectText;

p.addEventListener('mouseup', function() {
    rng = document.createRange();
    rng.selectNodeContents(p);
    selectText = window.getSelection();
    selectText.addRange(rng);
}, false);


document.body.lastElementChild.addEventListener('click', function() {
    selectText.removeRange(rng);
}, false);

Fiddle

我无法理解为什么该方法不起作用Selection.removeRange()?我们的想法是只保留原始选择。

1 个答案:

答案 0 :(得分:1)

safarigoogle-chrome中,您应该使用

selectText.removeAllRanges(rng)

工作fiddle