javascript - Js窗口根据另一个元素宽度调整改变元素宽度

标签 javascript html css

因此,当我每次调整窗口大小时,当我的屏幕尺寸低于 520px 时,我需要更改蓝色方 block 元素宽度。 蓝色方 block 应具有绿色方 block 宽度,但绿色方 block 宽度样式应以百分比表示。

我所做的一切都不起作用:(

window.addEventListener('resize', ()=> {
  if (screen.width < 520) {
    const boxElement = document.getElementsByClassName('box')[0].clientWidth,
      changingElement = document.getElementsByClassName('changing__width__element')[0];
    
    changingElement.style.width = `${boxElement}px`;
  }
}, true);
body,html{
  width: 100%;
  height: 100%;
}

.box{
  width: 80%;
  height: 80%;
  left: 10%;
  top: 10%;
  background: lime;
  display: flex;
  position: relative;
  align-items: center;
  justify-content: center;
}

.changing__width__element{
  width: 50px;
  height: 50px;
  background: blue;
  position: relative;
}
<body>
  <div class="box">
    <div class="changing__width__element"></div>
  </div>
</body>

最佳答案

如果你不想走CSS路线,这可能是最简单的解决方案,不要使用screen.width,使用window.innerWidth,你可以在这里阅读有关差异的更多信息:what-is-the-difference-between-window-innerwidth-and-screen-width

window.addEventListener('resize', ()=> {
  const boxElement = document.getElementsByClassName('box')[0].clientWidth,
      changingElement = document.getElementsByClassName('changing__width__element')[0];
  if (window.innerWidth < 520) {
    changingElement.style.width = `${boxElement}px`;
  } else  {
    changingElement.style.width = "50px";
  }
}, true);
body,html{
  width: 100%;
  height: 100%;
}

.box{
  width: 80%;
  height: 80%;
  left: 10%;
  top: 10%;
  background: lime;
  display: flex;
  position: relative;
  align-items: center;
  justify-content: center;
}

.changing__width__element{
  width: 50px;
  height: 50px;
  background: blue;
  position: relative;
}
<body>
  <div class="box">
    <div class="changing__width__element"></div>
  </div>
</body>

关于javascript - Js窗口根据另一个元素宽度调整改变元素宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72706064/

相关文章:

JavaScript 动画 - 在到达外部 div 边界时停止内部 div 移动

javascript - d3js 掩码在条形图上显示点

javascript - D3更新模式下select using merge和selectAll的区别

javascript - 生成并下载网页截图而不丢失样式

javascript - 将值写入页面而不出现在源代码中

javascript - css 选择器在浏览器中有效,但在 Selenium 中无效

javascript - SAPUI5:将 Controller 属性绑定(bind)到 View

javascript - 使用变量在 Highcharts 中设置仪表限制

html - Figure 和 Figcaption 的 CSS 问题

jquery - 仅为桌面设置样式(响应式站点)