So i need change blue square element width when my screen size below 520px evry time i am resising the window. The blue square should get green square width, but green square width style should be in percents.

Nothing works the way i am doing it :(

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相关问答推荐

详细说明如何以图表方式改变仪表的范围和 colored颜色

Vue-Router渲染组件但不更改网址

nPM审计始终发现0个漏洞

如何使用React渲染器放置根dis?

容器如何更改默认插槽中子项的显示?

当promise 在拒绝处理程序被锁定之前被拒绝时,为什么我们会得到未捕获的错误?

如何避免移动设备中出现虚假调整大小事件?

如何将连续的十六进制字符串拆分为以空间分隔的十六进制块,每个十六进制块包含32个二元组?

Phaser 3 console. log()特定游戏角色的瓷砖属性

如何从一个列表中创建一个2列的表?

Chromium会将URL与JS一起传递到V8吗?

在拖放时阻止文件打开

当用户点击保存按钮时,如何实现任务的更改?

将基元传递给THEN处理程序

如何使用<;Link>;执行与JS Reaction中的";window.Location=/GameOverDied;";类似的操作?

在验证和提交表单后使用useNavigate()进行react 重定向,使用带有加载器和操作的路由

OnClick更改Json数组JSX中的图像源

我怎样才能得到一个数组的名字在另一个数组?

为什么我的SoupRequest";被重置为初始值,以及如何修复它?

我在哪里添加过滤器值到这个函数?