gpt4 book ai didi

javascript - 如何在单击按钮时动态更改所选文本的颜色?

转载 作者:行者123 更新时间:2023-12-03 22:57:06 25 4
gpt4 key购买 nike

我正在使用以下代码来更改文本的颜色,但它不起作用。任何人都可以帮助我吗? javascript 或 jquery 中的解决方案一切都很好..

         var pinktext = "#cc0099";
document.execCommand("ForeColor", false, pinktext);

最佳答案

document.getElementById("change_color").onclick = function() {
// Get Selection
sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
// Set design mode to on
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Colorize text
document.execCommand("ForeColor", false, "red");
// Set design mode to off
document.designMode = "off";
}
<span id="content" contenteditable>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sit amet odio eu magna mattis vehicula. Duis egestas fermentum leo. Nunc eget dapibus eros, id egestas magna. Fusce non arcu non quam laoreet porttitor non non dui. Ut elit nisl, facilisis id hendrerit et, maximus at nunc. Fusce at consequat massa. Curabitur fermentum odio risus, vel egestas ligula rhoncus id. Nam pulvinar mollis consectetur. Aenean dictum ut tellus id fringilla. Maecenas rutrum ultrices leo, sed tincidunt massa tempus ac. Suspendisse potenti. Aenean eu tempus nisl.
</span>
<br/><br/>
<button id="change_color">Change Selected Text Color</button>

关于javascript - 如何在单击按钮时动态更改所选文本的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17288964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com