【问题标题】:How do I change the div size by clicking multiple button?如何通过单击多个按钮来更改 div 大小?
【发布时间】:2021-05-27 11:21:12
【问题描述】:

当有人点击相应的按钮时,我想改变 div 的大小。比如点击小按钮会使div宽度变为30%,点击中按钮会使div宽度变为50%。

我找到了这个Javascript: Change Div size on button click,但它对我不起作用,因为我不知道他的 HTML 结构,而且他使用的是 ID 而不是类。

下面是我的代码。请帮帮我:

body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 300px;
}

.Button_Container {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.Medium {
  margin: 0 15px;
}

.Content_Container {
  width: 100%;
  height: 150px;
  background-color: blue;
  margin-top: 30px;
}
<div class="Button_Container">
  <button class=">FULL" onclick="myFunction">FULL</button>
  <button class="Medium" onclick="myFunction">Medium</button>
  <button class="Small" onclick="myFunction">Small</button>
</div>

<div class="Content_Container"></div>

【问题讨论】:

  • myFunction 的实现在哪里
  • 抱歉,我正在学习 JavaScript,对它不太熟悉。所以我把它留空了。

标签: javascript


【解决方案1】:

function myFunction(width){

var all = document.getElementsByClassName('Content_Container');
for (var i = 0; i < all.length; i++) {
  all[i].style.width = width;
}
}
body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 300px;
}

.Button_Container {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.Medium {
  margin: 0 15px;
}

.Content_Container {
  width: 100%;
  height: 150px;
  background-color: blue;
  margin-top: 30px;
}
<div class="Button_Container">
  <button class=">FULL" onclick="myFunction('100%')">FULL</button>
  <button class="Medium" onclick="myFunction('70%')">Medium</button>
  <button class="Small" onclick="myFunction('50%')">Small</button>
</div>

<div class="Content_Container"></div>

【讨论】:

  • 我可以知道类而不是 ID 的用例吗?因为我有多个 div,我需要按类而不是 ID 来定位它。
  • 好的,我已经更改了课程代码。有帮助吗
猜你喜欢
  • 1970-01-01
  • 2019-12-03
  • 2012-10-24
  • 2022-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-21
  • 1970-01-01
相关资源
最近更新 更多