简体   繁体   English

在突出显示的元素上添加 class?

[英]Add class on highlighted elements?

Is it possible to add a class on highlighted elements?是否可以在突出显示的元素上添加 class? 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.例如:如果我 Select .block-2, .block-3, .block-4 ,然后按Enter键,那么所有这些块都应该添加一个新的 class。我的意思是我需要在突出显示选择时获取所有这些元素当按下Enter键时。

<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.您需要使用选项 api 来执行此操作。 You can use containsNode to do the rest, if your are ie9+.如果你是 ie9+,你可以使用containsNode来做 rest。

https://developer.mozilla.org/en-US/docs/Web/API/Selection https://developer.mozilla.org/zh-CN/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.假设您可以使用containsNode ,您应该只能监听keydown ,按Enter过滤,然后最终查询文档以进行选择并根据块节点是否包含在选择中来应用类。

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.这段代码在大约 3 分钟内拼凑在一起,不是最优的,应该在使用前进行审查。 You can see it in action @ https://jsfiddle.net/z0gh7eck/2/ .您可以在 @ https://jsfiddle.net/z0gh7eck/2/看到它的实际效果。

According to jandy's answer to stackovweflow .根据 jandy 对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.但是你可以绑定mouseup事件来检查是否有选择然后添加一个 class。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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