How can I highlight a word/term quicker and smarter?

后端 未结 6 750
误落风尘
误落风尘 2021-02-05 06:27

I have some text:

Hello world, Attack on Titan season two!

Currently, if a user wants to highlight a word/ter

6条回答
  •  深忆病人
    2021-02-05 07:15

    Concepts

    To select each word, there are something you must keep in mind first:

    1. textNode is a single sting contains all the words, you won't be able to select each "word", since it's not a DOM node.

    2. There is no specific event triggered in browser when you "drag and select" a word. However, when you drag & select, there are 2 events get fired: mouseover is triggered when you move your mouse, click is triggered when you release your mouse button. (This is true even in Mac's touchpad).

    3. There are different implementation on "highlight" when you select a word.

    Steps

    Based on the concepts, you have to do the following steps sequentially to achieve your goal:

    1. Get the words in paragraph and wrapped them with tag (e.g. ) for DOM selection
    2. When the click event is triggered (which indicate your select has ended), highlight the word you just select.

    The implementation would be something likes this (with jQuery). And you may see the live demo here:

    $(function() {
    
      // 1. When mouseover the paragraph, wrapped each word with 
      $('p').one('mouseover', function(event) {
        $('p').html(function(index, text) {
          var wordsArray = text.split(' ');
    
          var wrappedArray = wordsArray.map(function(val, index) {
            val = '' + val + '';
            return val;
          });
    
          var wrappedString = wrappedArray.join(' ');
    
          // 2. Replace the paragraph with wrapped text
          $(this).html(wrappedString);
    
          // 3. When the word is select, highlight the word
          $(this).children('span').on('click', function() {
            var selector = '.' + $(this).attr('class');
            SelectText(selector);
          });
        });
      });
    });
    
    
    function SelectText(element) {
      var doc = document,
        text = doc.querySelector(element),
        range, selection;
      if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
      } else if (window.getSelection) {
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
      }
    }
    
    

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Autem amet suscipit incidunt placeat dicta iure, perspiciatis libero nobis dolore, temporibus et! Quae fugiat necessitatibus ut, molestias aut. Sequi rerum earum facilis voluptates ratione architecto officia quod aut unde voluptas? Dignissimos ducimus exercitationem perspiciatis nam numquam minima accusamus quod necessitatibus amet illo vel vero placeat voluptate eos iste ratione veniam quisquam atque non voluptatum sint hic sed, suscipit. Doloremque officiis rerum sunt delectus unde odit eos quod earum aspernatur, tempora neque modi tempore minima maiores fuga eaque dolore quos minus veritatis aliquid, vel suscipit dolores. Voluptatem eius obcaecati, laborum ipsa a!

    SelectText function should attribute to @Jason in this post on SO: Selecting text in an element: akin to highlighting with your mouse

提交回复
热议问题