简体   繁体   中英

Add class on highlighted elements?

Is it possible to add a class on highlighted elements? For example: If I Select the .block-2, .block-3, .block-4 , and press Enter key then all of these blocks should add a new class. I mean I need to get all of these elements on highlight selection when pressed the Enter key.

<div class="root">
  <div class="block-1"> 1st </div>
  <div class="block-2"> 2nd </div>
  <div class="block-3"> 3rd </div>
  <div class="block-4"> 4th </div>
  <div class="block-5"> 5th </div>
</div>

在此处输入图像描述

Youll want to use the selections api to do this. You can use containsNode to do the rest, if your are ie9+.

https://developer.mozilla.org/en-US/docs/Web/API/Selection

Assuming you can use containsNode you should just be able to listen to keydown , filter by Enter , and then finaly query the document for the selection and apply classes depending on if the block nodes are contained within the selection.

const $root = document.querySelector('.root');

document.addEventListener('keydown', (e) => {
    if (e.code == "Enter") {
    const selection = document.getSelection();
    console.log(selection)
    for (const $child of $root.children) {
        if (selection.containsNode($child) || $child.contains(selection.anchorNode) || $child.contains(selection.focusNode)) {
        $child.classList.add('selected');
      } else {
        $child.classList.remove('selected');
      }
    }
  }
});

This code was thrown together in about 3 minutes, is sub optimal, and should be reviewed before being used. You can see it in action @ https://jsfiddle.net/z0gh7eck/2/ .

According to jandy's answer to stackovweflow . There is no event that "text was selected". But you can bind mouseup event to check if there was a selection then add a class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM