Py学习  »  Jquery

setInterval在不使用jquery的情况下逐个更改javascript中元素集的样式

paciekFly • 3 年前 • 1435 次点击  

我有一段代码,从JSON中提取数据,并将其分为四个部分。

有了这四个部分,我想在一个部分中添加一个边框2秒钟,然后移除边框并将其添加到另一个部分中。等等一旦边界到达最后一段,整个过程应该重新开始。

根据我在类似线程中读到的内容,我应该使用setInterval并通过循环向每个元素添加/删除类,但不确定如何编写它。有人能帮忙吗?

function completeAd(obj) {
  const offers = obj['offers'];

  for (let i = 0; i < 4; i++) {
    let rand = Math.floor((Math.random() * offers.length));

    const singleAd = document.createElement('section');
    singleAd.className = "adSection"
    const price = document.createElement('p');
    const imgURL = document.createElement('img')

    imgURL.src = "http:" + offers[rand].imgURL
    price.textContent = offers[rand].price + " " + offers[rand].currency;

    singleAd.appendChild(price);
    singleAd.appendChild(imgURL);

    adSection.appendChild(singleAd);

  }
}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129783
文章 [ 1 ]  |  最新文章 3 年前
mplungjan
Reply   •   1 楼
mplungjan    4 年前

是的,你需要在一段时间内添加和删除一个类

https://jsfiddle.net/mplungjan/pt68Lqoe/

const obj = {
offers : [ 
  { price:200, currency:"$", imgURL: "https://picsum.photos/200/200" },
  { price:300, currency:"$", imgURL: "https://picsum.photos/300/200" },
  { price:400, currency:"$", imgURL: "https://picsum.photos/400/200" },
  { price:500, currency:"$", imgURL: "https://picsum.photos/500/200" },
  { price:600, currency:"$", imgURL: "https://picsum.photos/600/200" }
]}


const fy = (a, b, c, d) => { c = a.length; while (c) b = Math.random() * (--c + 1) | 0, d = a[c], a[c] = a[b], a[b] = d}; // shuffle

fy(obj.offers); // shuffle them

window.addEventListener("load", () => {
  document.getElementById("adSections").innerHTML = obj.offers.slice(0, 4) // take the first 4
    .map(offer => `<section class="adSection"><p>${offer.price}${offer.currency}</p><img src="${offer.imgURL}" />`).join('');

  const sections = document.querySelectorAll(".adSection");
  let cnt = sections.length - 1;
  setInterval(function() {
    sections[cnt].classList.remove("active");
    cnt++;
    if (cnt >= sections.length) cnt = 0;
    sections[cnt].classList.add("active")
  }, 3000)

})
section {
  display: block;
  border: 1px solid white;
  width: 500px
}

.active {
  border: 1px solid black
}

img {
  height: 200px
}
<div id="adSections">


</div>