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

我使用以下代码来更改文本的颜色,但它不起作用..任何人都可以帮助我吗? 在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"; } 
  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.  

 the following code work when u select a text or word color will be change.  

试试这个

标记

 

I am using the following code to change the color of text but it is not working.. Can anyone help me with this? the soloution in javascript or jquery anything is fine..

脚本

  

在这里查看DEMO http://jsfiddle.net/yeyene/GYuBv/7/

选择文本,然后单击按钮以更改所选文本颜色。

 function selectHTML() { try { if (window.ActiveXObject) { var c = document.selection.createRange(); return c.htmlText; } var nNd = document.createElement("span"); var w = getSelection().getRangeAt(0); w.surroundContents(nNd); return nNd.innerHTML; } catch (e) { if (window.ActiveXObject) { return document.selection.createRange(); } else { return getSelection(); } } } $(function() { $('#changeColor').click( function() { var mytext = selectHTML(); // you can modify any css style here... $('span').css({"color":"red"}); }); }); 

我创建了一个非常简短的小提琴 ,演示了如何使用jQuery来改变一段文本的颜色。

HTML:

 

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium?

CSS:

 #paragraph { color: green; } 

JavaScript的:

 $('#colorChanger').click(function() { $('#paragraph').css('color','black'); }); 

上面的代码显示,使用任何文本,您可以使用jQuery的css方法更改颜色。 另外,我使用#paragraph访问段落; 但是,您可以通过jQuery使用nth-child,您可以使用循环遍历容器的子节点并检查正确的子节点然后使用jQuery中的css方法。 这些只是改变一段文字颜色的几种方法。