How to use the Javascript to add/remove the CSS/colour style to the html page?

后端 未结 2 602
悲哀的现实
悲哀的现实 2021-01-16 02:20

I have a simple javascript question in the HTML page.

In my case, the user can use the mouse to select some text in the paragrahe, e.g. us

2条回答
  •  没有蜡笔的小新
    2021-01-16 03:06

    This will do the trick to wrap the selected text with a node. I think you will need to change the getSelection() method in order to make it work in IE, but it works in FF:

    function colour(colour) {
      var selection= window.getSelection();
      if (selection.toString()!=="") {
        var range = selection.getRangeAt(0);
        var span = document.createElement("span");
        span.className = colour;
        span.innerHTML = range.toString();
        range.deleteContents();
        range.insertNode(span);
      }
    }
    

    EDIT: The other two functions:

    function clear_colour() {
      var selection=  window.getSelection();
      if (selection.toString()!=="" && 
          selection.anchorNode.parentNode.nodeName==="SPAN") {
        selection.anchorNode.parentNode.className="";
     }
    }
    
    function clear_colour_all() {
      var selection= document.getElementById('content');
      var spans = selection.getElementsByTagName("span");
      for(var i=0;i

    It have some weird behavior depending on how you select the text, but now you have something to work with ;)

提交回复
热议问题