我想更改已经选择的文本的颜色,当您选择某些文本时,您可以在此处看到http://jsfiddle.net/o533v4m6/,即使我更改了类别,但已经选择的颜色仍取决于类“ a”或“ b”文字不会改变,只有在我再次选择文字时才会改变。这是代码
<p class="a">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum repellat dolores iste ut animi magnam veritatis dignissimos porro magni quam. Facere ratione nulla vel placeat saepe molestias non porro illo.
</p>
的CSS
p.a::selection {
background-color: #C5979D !important;
color: #fff;
}
p.b::selection {
background-color: #77B28C !important;
color: #fff;
}
javascript
setInterval(function() {
$('p').toggleClass('a')
$('p').toggleClass('b')
}, 1000);
编辑:-
解决方案-更改类后,清除选择并再次选择http://jsfiddle.net/o533v4m6/1/
最佳答案
正如Hugo sousa的评论所说-更改班级后,我清除了所选内容并重新选择了文本。
$(function() {
$('#color').click(function() {
$('p').toggleClass('a')
$('p').toggleClass('b')
// Try to clear the selection and reselect the text
var selection = window.getSelection()
var elements = [];
var ranges = [];
if (selection.rangeCount) {
var i = selection.rangeCount
while (i--) {
ranges[i] = selection.getRangeAt(i).cloneRange();
}
selection.removeAllRanges()
i = ranges.length;
while (i--)
{
selection.addRange(ranges[i]);
}
}
});
})