Use JS to achieve a simple news upward carousel effect

Recently, I encountered a requirement in the digital large screen project, which is to realize a function. The specific content is to write a function similar to the news carousel, limited news titles, cyclic carousel, and corresponding to the process of carousel, each The jump address corresponding to the title cannot be changed and must belong to the news.

First prepare a div, set the content to be displayed inside

div class="panel line1" style="overflow:hidden">
        <h2>新闻动态</h2>
        <div class="app">
          <a href="https://www.acwing.com/" target="_blank">acwing官网</a><br>
          <a href="https://www.baidu.com/" target="_blank">百度</a><br>
          <a href="https://www.csdn.net/" target="_blank">csdn官网</a><br>
          <a href="https://cn.vuejs.org/" target="_blank">vue3官网</a><br>
          <a href="http://element-plus.org/zh-CN/" target="_blank">elementplus官网</a><br>
        </div>
</div>

Simply specify the style of the a tag

  a {
      text-decoration: none;
      color: #22cbda;
      display: inline-block;
      width: 100%;
      height: 40px;
      line-height: 40px;
      background-image: url('./images/jpg.jpg');
      margin-top: 10px;
}

General idea:

First define a timer, then get the label to be rotated, get the value in it, and traverse each node. First, when i=0, define an intermediate variable temp, record the content of the first position element, and then define a variable hrefTemp, store the value of its href. When i<length of element -1, the value of the following element is assigned to the previous one, and the href attribute is the same. Then when i = length of the element - 1, assign temp and hrefTemp to the last variable respectively. This is the general analysis process of this requirement, and then the code is implemented. Below is the code implementation.

Code:

  <script>
    let aElement = document.querySelectorAll('.line1 a')
    setInterval(function () {
      for (let i = 0; i < aElement.length; i++) {
        if (i === 0) {
          temp = aElement[0].innerHTML
          tempSrc = aElement[0].getAttribute("href")
        }
        if (i < aElement.length - 1) {
          aElement[i].innerHTML = aElement[i + 1].innerHTML
          aElement[i].setAttribute("href", aElement[i + 1].getAttribute("href"))
        }
        if (i === aElement.length - 1) {
          aElement[aElement.length - 1].innerHTML = temp
          aElement[aElement.length - 1].setAttribute('href', tempSrc)
        }
      }
    }, 3500)
  </script>

Show results:

ok, so you can achieve the desired function!

Guess you like

Origin blog.csdn.net/Yajyaj123/article/details/126907177