将CSS类应用于内容中的选定文本可编辑div
问题描述:
我试图在按下按钮时将类添加到所选文本。现在,出于某种原因,我的代码在按下按钮时将该类应用于按钮,但我希望它应用于选定的文本本身。将CSS类应用于内容中的选定文本可编辑div
这是我有:
我需要的按钮是一个div
,这可能可能是问题,但我只是想突出显示的文本,以获取类,而不是按钮。
谢谢...
function addAnimation() {
document.execCommand('formatblock', false, 'span');
selectedElement = window.getSelection().focusNode.parentNode;
selectedElement.className += "grad";
}
.textField {
background: #333;
color: #fff;
width: 300px;
height: 300px;
}
.grad {
-webkit-animation: changeColor 8s ease-in infinite;
animation: changeColor 8s ease-in infinite;
}
@-webkit-keyframes changeColor {
0% {color: #ff7473;}
25% {color: #ffc952;}
50% {color: #fc913a}
75% {color: #75D701;}
100% {color: #ff7473}
}
<div class="textField" contenteditable="true">Hello world. Select this text and press the button</div>
<div onclick="addAnimation()">Animate
</div>
答
当您单击虚拟按钮,然后选择不见了。你需要这种方式绑定到mousedown
事件:
function addAnimation() {
selectedElement = window.getSelection().focusNode.parentNode;
$(selectedElement).addClass('grad');
}
$('.animate-selected').on('mousedown', addAnimation);
.text-field {
background: #333;
color: #fff;
width: 300px;
height: 100px;
}
.grad {
-webkit-animation: changeColor 8s ease-in infinite;
animation: changeColor 8s ease-in infinite;
}
.animate-selected{
margin: 2px 0;
border: 1px solid blue;
display: inline-block;
padding: 0 4px;
cursor: pointer;
}
@-webkit-keyframes changeColor {
0% {
color: #ff7473;
}
25% {
color: #ffc952;
}
50% {
color: #fc913a
}
75% {
color: #75D701;
}
100% {
color: #ff7473
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-field" contenteditable="true">
Hello world. Select this text and press the button
</div>
<div class="animate-selected">
Animate
</div>
同样在JSFiddle。
如果你想动画只选定的文本,比你做这种方式:
function addAnimation() {
$('.grad').contents().unwrap(); /* this removes previous animation */
var selectedText = window.getSelection();
var container = $(selectedText.anchorNode.parentNode);
var wrappedText = '<span class="grad">' + selectedText + '</span>'
container.html(container.html().replace(selectedText, wrappedText));
}
$('.animate-selected').on('mousedown', function(e) {
addAnimation();
});
.text-field {
background: #333;
color: #fff;
width: 300px;
height: 100px;
}
.grad {
-webkit-animation: changeColor 8s ease-in infinite;
animation: changeColor 8s ease-in infinite;
}
.animate-selected{
margin: 2px 0;
border: 1px solid blue;
display: inline-block;
padding: 0 4px;
cursor: pointer;
}
@-webkit-keyframes changeColor {
0% {
color: #ff7473;
}
25% {
color: #ffc952;
}
50% {
color: #fc913a
}
75% {
color: #75D701;
}
100% {
color: #ff7473
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-field" contenteditable="true">
Hello world. Select this text and press the button
</div>
<div class="animate-selected">
Animate
</div>
同样在JSFiddle。
当你点击按钮时,它比选定的元素更宽泛,以防止它。 – skobaljic