简体   繁体   中英

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

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:

当前状态

Desired 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:

    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:

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

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);
  });
}

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