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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17288964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:46:14  来源:igfitidea点击:

How to change color of the selected text dynamically on click of button?

javascriptjqueryhtmljquery-mobile

提问by user1844039

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..

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

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

回答by NETCreator Hosting

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>

回答by user1844039

The following code works when you select a text or word, the color will change:

以下代码在您选择文本或单词时起作用,颜色会改变:

<style>
::selection {
    color:blue;
    background:yellow;
    font-size:14px;
}

::-moz-selection {
    color:blue;
    background:yellow;
    font-size:14px;
}
</style>

回答by yeyene

Check DEMO here http://jsfiddle.net/yeyene/GYuBv/7/

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

Select text, and click button to change selected text color.

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

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"});
    });
});

回答by Shinov T

Try this

试试这个

mark up

标记

<p>
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..
</p>

Script

脚本

<script type="text/javascript" >

   $(document).ready(function(){
       $("p").on("mouseup" , function(){
          selectedtext = selectedText();
          var replceText = "<span style='background:#cccccc' >"+selectedtext+"</span>";
          var gethtmlText = $(this).text();
          var replcedtext = gethtmlText.replace(selectedtext ,  replceText);
         $(this).html(replcedtext)
       });
 });

function selectedText(){
    if(document.getSelection){
      return document.getSelection();
    }
    else if(document.selection){
      return document.selection.createRange().text;
    }
}

</script>

回答by Ilan Biala

I've created a pretty short fiddlethat demonstrates the use of jQuery to change the color of a piece of text.

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

HTML:

HTML:

<p id="paragraph">Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium?</p>
<button id="colorChanger">This Button changes the text color of the paragraph.</button>

CSS:

CSS:

#paragraph {
    color: green;
}

JavaScript:

JavaScript:

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

The code above shows that with any text you can change the color using jQuery's css method. Additionally, I used #paragraphto access the paragraph; however, you can use nth-child through jQuery, you can cycle through the children of a container using a loop and checking for the right one then using the css method from jQuery. These are just a few of the ways to change the color of a piece of text.

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