简体   繁体   English

Javascript - 在跨度范围之上添加一个新的 DIV

[英]Javascript - add a new DIV above a range of spans

I have the following code on codesandbox: https://codesandbox.io/s/highlighter-cv2kv?file=/src/index.js我在codesandbox上有以下代码: https://codesandbox.io/s/highlighter-cv2kv?file=/src/index.js

I have a bunch of spans for every word in a phrase.我对短语中的每个单词都有一堆跨度。 I want to be able to create highlights based on a start and end time (every span has those details in dataset).我希望能够根据开始时间和结束时间创建亮点(每个跨度在数据集中都有这些详细信息)。 Highlights need to be laid above the corresponding spans.需要在相应的跨度上方放置高亮显示。

So far I've been able to highlight the start and stop word but I need to highlight every word between that interval.到目前为止,我已经能够突出显示起始词和停止词,但我需要突出显示该间隔之间的每个词。

Current state:当前state:

当前状态

Desired state:所需 state:

理想状态

Any ideas on how can I do this in the most efficient way?关于如何以最有效的方式执行此操作的任何想法?

i have an i idea for you less js more css, with that you only need to toggle the class playing and will highlight the words:我有一个我的想法给你 less js more css,你只需要切换 class playing并突出显示这些词:

    body {
  font-family: sans-serif;
}

.will-play {
  position: inherit;
  z-index: 1;
  position: relative;
}
.will-play.playing::after {
  z-index: 200;
  position: absolute;
  top: 0;
  left: 0;

  height: 100%;
  width: 100%;
  background-color: yellow;
  opacity: 0.5;
  content: "";
}

I forgot the JS:我忘记了JS:

let ranges = { start: "80.9", end: "87.48" };


let spans = [...document.querySelectorAll("span.will-play")];

spans.map((item) => {
  if(item.dataset.start>=ranges.start && item.dataset.end<=ranges.end){
    item.classList.add('playing')
  }
});

Using dataset and querySelectorAll使用datasetquerySelectorAll

Working Demo 工作演示

for (let range of ranges) {
  parent.querySelectorAll('.will-play').forEach (span => {
    if (span.dataset.start < range.start || span.dataset.end > range.end) {
      return;
    }

    let highLightParent = document.createElement("div");    
    let highlight = document.createElement("div");
    let pos = getPos(parent, span);
    highlight.style.cssText = `position: absolute; top: ${pos.top}px; left: ${pos.left}px; width: ${span.offsetWidth}px; height: ${span.offsetHeight}px; background-color: yellow; opacity: 0.5; z-index: 1`;

    highLightParent.appendChild(highlight);    
    parent.appendChild(highLightParent);
  });
}

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

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