使用jquery和bootstrap检测内容大小

时间:2018-12-20 09:34:06

标签: javascript jquery twitter-bootstrap

我正在尝试实现一个幻灯片页面以进行服务监视。在页面上,将有一系列DIV,其高度相同但宽度不同(设置了max-width属性)。这些DIV使用inline-block显示。

我的问题是,我要显示200张卡片,而显示器只能显示几十张卡片。不知道显示端口的大小以及每张卡的确切大小(因为它们不同),如何知道幻灯片上要显示多少张卡,从而不会显示滚动条?

伪代码,例如:

function showSlide(cards, index) {
    clearSlide()
    while (index < cards.length) {
        showCard(cards[index])
        index++
        if (noMoreSpaceOnPage()) {
            break
        }
    }
    return index
}

cards = getCards()
var index = 0
setInterval(30000, function() {
        next = showSlide(cards, index)
        if (next >= index) {
            index = 0
        } else {
            index = next
        }
})

1 个答案:

答案 0 :(得分:2)

您可以轻松获得视口宽度(document.documentElement.clientWidth是窗口/框架的宽度(以像素为单位,不带滚动条))以及每张卡的宽度(offsetWidth属性):

const cards = document.querySelectorAll("div");

const viewportWidth = () =>  document.documentElement.clientWidth;

const cardWidth = card => card.offsetWidth;

const cardsThatWillFit = (cards, viewportWidth) => {
  let remainingWidth = viewportWidth;
  const fittableCards = [];
  for (let i = 0; i < cards.length; i++) { // this is uglier than forEach, but it supports break, so…
    remainingWidth = remainingWidth - cardWidth(cards[i]);
    if (remainingWidth > 0) {
      fittableCards.push(cards[i]);
    } else {
      break;
    }
  };
  return fittableCards;
};


const logInfo = () => {
  console.log("viewport width:", viewportWidth());
  cards.forEach((card, index) => console.log(`card ${index + 1} width:`, cardWidth(card)));
  console.log("cards that will fit:", cardsThatWillFit(cards, viewportWidth()).map((card, index) => index + 1).join(" "));
  console.log("-------------")
}

document.querySelector("button").addEventListener("click", () => {
  cards.forEach(card => card.style.width = Math.random() * 8 + "em");
  logInfo();
})

logInfo();
body {
  padding: 0;
  box-sizing: border-box;
}

nav {
  display: flex;
  flex-wrap: wrap;
}

nav div {
  padding: 3em;
  border: 1px solid hotpink;
  text-align: center;
  width: 5em;
  display: inline-block;
}
<button>randomize widths</button>
<nav>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</nav>

别忘了在卡之间添加任何边距到计算中。并根据需要重新调整窗口大小。