从数组滚动到每个标记标签并将其显示在屏幕上

问题描述

在我的代码中,我正在搜索一些单词并使用 mark 标记突出显示它们。

我想使用下一个按钮滚动到标记标签中包含的每个突出显示的单词,但我不确定如何准确进行。

我试过了:

// select btn id to execute function
$('#btnNext').click(test);
//function
        function test() {
//obtain a nodeList
            let pickHighlights = document.querySelectorAll('mark');
// convert nodeList to array
            let pHtest=  Array.from(pickHighlights);
// apply scroll to highlighted tags
            pHtest.forEach(function(){
                //scroll to highlighted mark
                var offset = $('.timeline-compendium__content').offset().top;
                window.scrollTo(0,offset);
                //scroll to next one
                // ???
            })
        }

解决方法

您可以存储当前引用的元素的索引,下面的示例将其存储到变量 i

$(document).ready(function () {
  // console.log(occurrences);

  $(document).on("click","#findWord",function (e) {
    let occurrences = [];
    e.preventDefault();
    // clear();
    let x = document.querySelector("#searchedWord").value;
    let error = document.querySelector("#message");
    if (x == "") {
      error.style.display = "block";
      error.style.color = "red";
    } else {
      error.style.display = "none";
      highlightWord();
      displayOcc();
    }
    // let clickInput = document.querySelector('#searchedWord');
    let clickClear = document.querySelector("#clear");

    // Make clear button to appear on input field click
    // clickInput.addEventListener('input',function(){
    //     clickClear.style.display = 'block';
    // });

    clickClear.addEventListener("click",clear);

    function clear() {
      // get the search term from the input
      let clickInput = document.querySelector("#searchedWord");
      clickInput.value = "";
      var spans = $(".reports-list-item__title--compendium > mark");
      // console.log(spans);
      spans.each(function () {
        spans.contents().unwrap();
      });
      occurrences.splice(0,occurrences.length);
      // reset our labels
      $("#count").html("");
      $("#current").html("");
      $(".timeline-compendium__content").collapse("hide");
      $(".timeline-type .timeline-type__content").collapse("hide");
    }

    function highlightWord() {
      // create a regex from our term
      const word = document.getElementById("searchedWord").value;
      const r = new RegExp("(" + word + ")","ig");
      $(".reports-list-item__title--compendium").each(function (i) {
        if ($(this).text().match(r)) {
          // console.log($(this).text().match(r));
          // get all the matches
          var matches = $(this).text().match(r);
          // console.log(matches);
          // loop through them
          $.each(matches,function () {
            // push the index of this section onto the array
            occurrences.push(i);
            // console.log(occurrences);
          });
          // wrap each found search term with our `found` span to highlight it
          $(this).html($(this).text().replace(r,"<mark>$&</mark>"));
          $(this).closest(".timeline-compendium__content").collapse("show");
          // scroll to highlighted word(s)
          // $(this).closest(".timeline-compendium__content")[0].scrollIntoView();
          $(this)
            .closest(".timeline-type .timeline-type__content")
            .collapse("show");
        }
      });
    }

    function displayOcc() {
      let lengthOccurrences = occurrences.length;
      console.log(
        "Length (number) of occurrences is:" + " " + lengthOccurrences
      );

      let currViewMatch = Number(
        document.querySelector("#current").textContent
      );
      console.log("Number of current viewed match is:" + " " + currViewMatch);

      // if we are currently viewing a match,increment so we move to the next one
      currViewMatch = currViewMatch > 0 ? currViewMatch + 1 : 0;
      // if the incremented number is higher than the number of matches,reset it to 0
      currViewMatch = currViewMatch > lengthOccurrences ? 1 : currViewMatch;
      // if this is the first click and we found matches,set current to the first match
      currViewMatch =
        currViewMatch == 0 && lengthOccurrences > 0 ? 1 : currViewMatch;

      let insertNbrOcc =
        lengthOccurrences > 0 ? " of " + lengthOccurrences : " matches found";
      // // set number of matches found
      let count = document.querySelector("#count");
      count.textContent = insertNbrOcc;

      // // set  number of currently viewed match
      let nbrViewMatch = document.querySelector("#current");
      nbrViewMatch.textContent = currViewMatch;
    }
  });
  $("#btnNext").click(test);

  let i = 0;
  function test() {
    let pickHighlights = document.querySelectorAll("mark");
    var viewportOffset = pickHighlights[i].getBoundingClientRect();
    // these are relative to the viewport
    var top = viewportOffset.top;
    window.scrollTo(0,top);

    i++;

    if (i >= pickHighlights.length) {
      i = 0;
    }
  }
});
.found {
  background-color: yellow;
}

#labels {
  margin-left: 15px;
  font-size: 16px;
}
.timeline-compendium {
  margin-left: 2rem;
}

.timeline-type__header {
  width: 400px;
  height: 50px;
  background-color: rgb(46,177,100);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  border: 1px solid white;
}
.timeline-type__header:hover {
  color: white;
  background-color: rgb(35,119,70);
}

#tab-content {
  border: 1px solid red;
}
input[type="text"] {
  width: 80%;
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
}

input#findWord {
  background-color: rgb(248,211,3);
  border: none;
  color: black;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}

#clear {
  width: 25px;
  height: 25px;
  position: absolute;
  top: 20px;
  right: 150px;
  line-height: 25px;
  font-size: 14px;
  padding-left: 8px;
  font-weight: bold;
  cursor: pointer;
  color: #fff;
  background-color: red;
  border: none;
  border-radius: 50%;
}

#message {
  display: none;
  font-size: 1em;
}
#btnNext {
  margin-left: 0.5rem;
}
mark {
  background-color: yellow !important;
}
.stickyBar {
  position: sticky;
  top: 0;
  z-index: 1;
  background-color: white;
}
<html>
  <head>
    <link
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="row stickyBar">
        <div class="col-sm-12 mb-2">
          <div id="searchForm" class="d-flex flex-column">
            <label for="searchedWord">Search... </label>
            <div class="col-sm-12 p-0 d-flex">
              <input
                type="text"
                id="searchedWord"
                placeholder="Search..."
                aria-labelledby="searchedWord"
                value="cool"
                class="form-control form-control-lg"
              />
              <button type="submit" id="findWord" class="btn btn-primary">
                Search
              </button>
              <!-- next btn -->
              <input type="button" id="btnNext" value="next" />
              <div id="clear" role="button">X</div>
            </div>
          </div>
        </div>
        <div class="col-sm-6 mb-2">
          <div id="labels">
            <span id="current"></span>
            <span id="count"></span>
            <small role="alert" id="message" aria-hidden="true"
              >Please enter a word to start searching</small
            >
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col">
          <section class="timeline-compendium">
            <a
              class="btn timeline-compendium__header"
              data-toggle="collapse"
              href="#introduction"
              role="button"
              aria-expanded="true"
              aria-controls="introduction"
            >
              <div class="row align-items-center">
                <div class="col-auto">1<sup>st</sup> collapsible item</div>
                <div class="col"><span></span></div>
                <div class="col-auto">
                  <em
                    class="icon-arrow-down"
                    data-toggle="tooltip"
                    title="Collapse/expand"
                    data-delay="400"
                    aria-hidden="true"
                    data-original-title="Collapse/expand"
                  ></em
                  ><span class="sr-only">Collapse/expand this item</span>
                </div>
              </div>
            </a>
            <div
              class="timeline-compendium__content collapse"
              id="introduction"
            >
              <div class="timeline-type">
                <a
                  data-toggle="collapse"
                  href="#foreword"
                  role="button"
                  aria-expanded="false"
                  aria-controls="foreword"
                >
                  <div class="row no-gutters align-items-center">
                    <div class="col">
                      <div
                        class="
                          timeline-type__header timeline-type__header--title
                        "
                      >
                        <div class="row align-items-center">
                          <div class="col-auto timeline-type__chapter">1</div>
                          <div class="col timeline-type__title">
                            First nested collapsible
                          </div>
                          <div class="col-auto">
                            <em
                              class="icon-arrow-down"
                              data-toggle="tooltip"
                              title="Collapse/expand"
                              data-delay="400"
                              aria-hidden="true"
                            ></em
                            ><span class="sr-only"
                              >Collapse/expand this item</span
                            >
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </a>
                <div class="timeline-type__content collapse" id="foreword">
                  <ul class="reports-list">
                    <li>
                      <a
                        href="#"
                        target="_blank"
                        class="reports-list-item reports-list-item--compendium"
                      >
                        <div
                          class="
                            col-auto
                            reports-list-item__title
                            reports-list-item__title--compendium
                          "
                        >
                          First cool
                        </div>
                        <div class="reports-list-item__url">
                          <em
                            class="icon-url"
                            data-toggle="tooltip"
                            title="Link"
                            data-delay="400"
                            aria-hidden="true"
                          ></em>
                        </div>
                      </a>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </section>
          <!-- section 2 -->
          <section class="timeline-compendium">
            <a
              class="btn timeline-compendium__header collapsed"
              data-toggle="collapse"
              href="#titleA"
              role="button"
              aria-expanded="false"
              aria-controls="titleA"
            >
              <div class="row align-items-center">
                <div class="col-auto">2<sup>nd</sup></div>
                <div class="col"><span>collapsible item</span></div>
                <div class="col-auto">
                  <em
                    class="icon-arrow-down"
                    data-toggle="tooltip"
                    title="Collapse/expand"
                    data-delay="400"
                    aria-hidden="true"
                    data-original-title="Collapse/expand"
                  ></em
                  ><span class="sr-only">Collapse/expand this item</span>
                </div>
              </div>
            </a>
            <div class="timeline-compendium__content collapse" id="titleA">
              <div class="timeline-type">
                <a
                  class="accordion"
                  data-toggle="collapse"
                  href="#summary"
                  role="button"
                  aria-expanded="false"
                  aria-controls="summary"
                  class="collapsed"
                >
                  <div class="row no-gutters align-items-center">
                    <div class="col">
                      <div
                        class="
                          timeline-type__header timeline-type__header--title
                        "
                      >
                        <div class="row align-items-center">
                          <div class="col-auto timeline-type__chapter">2</div>
                          <div class="col timeline-type__title">
                            Second nested collapsible
                          </div>
                          <div class="col-auto">
                            <em
                              class="icon-arrow-down"
                              data-toggle="tooltip"
                              title="Collapse/expand"
                              data-delay="400"
                              aria-hidden="true"
                            ></em
                            ><span class="sr-only"
                              >Collapse/expand this item</span
                            >
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </a>
                <div class="timeline-type__content collapse" id="summary">
                  <ul class="reports-list">
                    <li>
                      <a
                        href="#"
                        target="_blank"
                        class="reports-list-item reports-list-item--compendium"
                      >
                        <div
                          class="
                            col-auto
                            reports-list-item__title
                            reports-list-item__title--compendium
                          "
                        >
                          Second cool
                        </div>
                        <div class="reports-list-item__url">
                          <em
                            class="icon-url"
                            data-toggle="tooltip"
                            title="Link"
                            data-delay="400"
                            aria-hidden="true"
                          ></em>
                        </div>
                      </a>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </section>
          <!-- section 3 -->
          <section class="timeline-compendium">
            <a
              class="btn timeline-compendium__header collapsed"
              data-toggle="collapse"
              href="#titleB"
              role="button"
              aria-expanded="false"
              aria-controls="titleB"
            >
              <div class="row align-items-center">
                <div class="col-auto">3<sup>rd</sup></div>
                <div class="col"><span>collapsible item</span></div>
                <div class="col-auto">
                  <em
                    class="icon-arrow-down"
                    data-toggle="tooltip"
                    title="Collapse/expand"
                    data-delay="400"
                    aria-hidden="true"
                  ></em
                  ><span class="sr-only">Collapse/expand this item</span>
                </div>
              </div>
            </a>

            <div class="timeline-compendium__content collapse" id="titleB">
              <div class="timeline-type">
                <a
                  data-toggle="collapse"
                  href="#chapterB0"
                  role="button"
                  aria-expanded="false"
                  aria-controls="chapterB0"
                  class="collapsed"
                >
                  <div class="row no-gutters align-items-center">
                    <div class="col">
                      <div
                        class="
                          timeline-type__header timeline-type__header--title
                        "
                      >
                        <div class="row align-items-center">
                          <div class="col-auto timeline-type__chapter">3</div>
                          <div class="col timeline-type__title">
                            Third nested collapsible
                          </div>
                          <div class="col-auto">
                            <em
                              class="icon-arrow-down"
                              data-toggle="tooltip"
                              title="Collapse/expand"
                              data-delay="400"
                              aria-hidden="true"
                            ></em
                            ><span class="sr-only"
                              >Collapse/expand this item</span
                            >
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </a>
                <div class="timeline-type__content collapse" id="chapterB0">
                  <ul class="reports-list">
                    <li>
                      <a
                        class="reports-list-item reports-list-item--compendium"
                      >
                        <div
                          class="
                            col-auto
                            reports-list-item__title
                            reports-list-item__title--nolink
                          "
                        >
                          No link
                        </div>
                      </a>
                    </li>
                    <li>
                      <a
                        href="#"
                        target="_blank"
                        class="reports-list-item reports-list-item--compendium"
                      >
                        <div
                          class="
                            col-auto
                            reports-list-item__title
                            reports-list-item__title--compendium
                          "
                        >
                          Some content with link cool
                        </div>
                        <div class="reports-list-item__url">
                          <em
                            class="icon-url"
                            data-toggle="tooltip"
                            title="Link"
                            data-delay="400"
                            aria-hidden="true"
                          ></em>
                        </div>
                      </a>
                    </li>
                    <li>
                      <a
                        href="#"
                        target="_blank"
                        class="reports-list-item reports-list-item--compendium"
                      >
                        <div
                          class="
                            col-auto
                            reports-list-item__title
                            reports-list-item__title--compendium
                          "
                        >
                          Some content with link
                        </div>
                        <div class="reports-list-item__url">
                          <em
                            class="icon-url"
                            data-toggle="tooltip"
                            title="Link"
                            data-delay="400"
                            aria-hidden="true"
                          ></em>
                        </div>
                      </a>
                    </li>
                  </ul>
                </div>
              </div>
              <div class="timeline-type">
                <a
                  data-toggle="collapse"
                  href="#chapterB2"
                  role="button"
                  aria-expanded="false"
                  aria-controls="chapterB2"
                  class="collapsed"
                >
                  <div class="row no-gutters align-items-center">
                    <div class="col">
                      <div
                        class="
                          timeline-type__header timeline-type__header--title
                        "
                      >
                        <div class="row align-items-center">
                          <div class="col-auto timeline-type__chapter">4</div>
                          <div class="col timeline-type__title">
                            Fourth nested collapsible
                          </div>
                          <div class="col-auto">
                            <em
                              class="icon-arrow-down"
                              data-toggle="tooltip"
                              title="Collapse/expand"
                              data-delay="400"
                              aria-hidden="true"
                            ></em
                            ><span class="sr-only"
                              >Collapse/expand this item</span
                            >
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </a>
                <div class="timeline-type__content collapse" id="chapterB2">
                  <ul class="reports-list">
                    <li>
                      <a
                        class="reports-list-item reports-list-item--compendium"
                      >
                        <div
                          class="
                            col
                            reports-list-item__title
                            reports-list-item__title--nolink
                          "
                        >
                          No link
                        </div>
                      </a>
                    </li>
                    <li>
                      <a
                        href="#"
                        class="reports-list-item reports-list-item--compendium"
                      >
                        <div
                          class="
                            col-auto
                            reports-list-item__title
                            reports-list-item__title--compendium
                          "
                        >
                          Some content with link
                        </div>
                        <div class="reports-list-item__url">
                          <em
                            class="icon-url"
                            data-toggle="tooltip"
                            title="Link"
                            data-delay="400"
                            aria-hidden="true"
                          ></em>
                        </div>
                      </a>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </section>
        </div>
      </div>
    </div>
  </body>
</html>