我试图在用户选择文本时实现一项功能,用户可以使用颜色选择器更改文本颜色,并且该更改应该是永久性的,直到他/她再次选择文本更改颜色。我能够更改整个文本的颜色,但无法弄清楚如何更改选择文本。我在 StackOverflow 上检查了很多问题,但找不到解决方案。这是我的文件
var box = document.getElementById('Myelement');
let colorpicker = document.getElementById('ColorPicker1');
setInterval(() => {
let color = colorpicker.value;
box.style.color = color;
}, 200);
/* function selectText(hexColor) {
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement('span');
span.style.color = hexColor;
span.className = 'selected-text';
span.appendChild(selectedText);
selection.insertNode(span);
}
function unselectText(){
$('#Myelement').find('.selected-text').contents().unwrap();
}
$(document).on('mouseup', function () {
selectText('#f90');
});
$(document).on('mousedown', function () {
unselectText();
});
*/
<html>
<head>
</head>
<body>
<p id="Myelement" contenteditable = "true">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>
<input name="MyColorPicker"
type="color"
id="ColorPicker1" />
<script>
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</body>
</html>
你基本上就在那里,除了这是input
颜色选择器上的一个事件
var box = document.getElementById('Myelement');
let colorpicker = document.getElementById('ColorPicker1');
colorpicker.addEventListener('input', function(e) {
selObj = window.getSelection()
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement('span');
span.style.color = e.target.value;
span.className = 'selected-text';
span.appendChild(selectedText);
selection.insertNode(span);
})
<html>
<head>
</head>
<body>
<p id="Myelement" contenteditable="true">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</p>
<input name="MyColorPicker" type="color" id="ColorPicker1" />
<script>
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句