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

后端 未结 5 1725
时光取名叫无心
时光取名叫无心 2020-12-18 07:20

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

5条回答
  •  伪装坚强ぢ
    2020-12-18 08:10

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

提交回复
热议问题