【问题标题】:Automatic Resizing Function自动调整大小功能
【发布时间】:2020-04-25 20:51:18
【问题描述】:

所以我有一个栏,其中包含许多较小的 div,每个都有相同的类。

.outer-bar{
  width: 100%;
  height: 50px;
  background-color: blue;
}

.outer-bar button {
  width: 50px;
  height: 40px;
  outline: none;
  background-color: white;
  border: none;
  margin-top: 5px;
  margin-bottom: 5px;
  float: left;
  margin-left: 2px;
}
<div class = "outer-bar">
  <button class = "a">Hi</button>
  <button class = "a">Hi</button>
  <button class = "a">Hi</button>
  <button class = "a">Hi</button>
  <button class = "a">Hi</button>
  <button class = "a">Hi</button>
  <button class = "a">Hi</button>
  <button class = "a">Hi</button>
  <button class = "a">Hi</button>
</div>

当窗口调整大小时,我希望窗口只显示足够多的没有溢出的窗口,但有尽可能多的。

那么使用:window.addEventListener("resize", function() {} );,有什么方法可以实现吗?

我看到的一个很好的例子是Google Docs,他们的栏会自动调整。

我更喜欢使用 Javascript 和 CSS 而不是 Jquery 或外部库来执行此操作。 (请注意,尽管基本思想仍然相同,但出于说明目的,我简化了元素的宽度和数量)。我也更喜欢使用 for 循环和document.getElementsByClassName("a")

我已经开始使用了:

var ribbon = document.getElementsByClassName("outer-bar")[0];
var prevChild = 0;
for(var i = 0; i < ribbon.children.length; i++) {
    if(ribbon.children[i].getBoundingClientRect().right < prevChild) {
        for(var c = i; c < ribbon.children.length; c++) {
            ribbon.children[c].style.display = "none";
        }
        break;
    }
    prevChild = ribbon.children[i].getBoundingClientRect().right;
}

尽管一旦我将窗口大小调整为更大,该方法不会使子项显示出来。

【问题讨论】:

  • 如果您知道色带长度,为什么不将其除以您希望按钮的尺寸。然后遍历按钮,使第一个(功能区长度/大小)块,其余的都没有。
  • 确定正确。

标签: javascript html css resize


【解决方案1】:

如果您知道丝带长度,为什么不将其除以您希望按钮的尺寸。然后遍历按钮,使第一个(色带长度/尺寸)块,其余的都没有。

【讨论】:

    【解决方案2】:

    我不确定我是否理解正确,但是当屏幕调整大小时,您似乎需要对内部 div 进行不同的样式设置。 CSS 能够为您处理此问题,而无需使用 JavaScript。

    Media Queries 可让您根据窗口的当前大小指定不同的样式。

    .outer-bar button {
      width: 50px;
      height: 40px;
      outline: none;
      background-color: white;
      border: none;
      margin-top: 5px;
      margin-bottom: 5px;
      float: left;
      margin-left: 2px;
    }
    
    @media screen and (max-width: 600px) {
      .outer-bar button {
        /* 
        Specify here any different styling 
        Ex. 
        */
    
        width: 25px;
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-09
      • 2012-04-11
      • 2011-08-23
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多