[英]Js window resize changing element width based on another elemnt width
因此,当我的屏幕尺寸低于 520 像素时,我需要更改蓝色方形元素的宽度,每次我重新调整窗口时。 蓝色方块应该得到绿色方块宽度,但绿色方块宽度样式应该是百分比。
没有什么能像我这样做的:(
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>
无需为此使用 JavaScript。 如果窗口的大小小于520px
,只需使用媒体查询并将width
更改为100%
。
根据屏幕大小更改某些内容通常没那么有用。
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; } @media (max-width: 520px) { .changing__width__element { width: 100%; } }
<body> <div class="box"> <div class="changing__width__element"></div> </div> </body>
通常,如果您设计某些东西,建议使用“移动优先”(或更好的小窗口优先),并使用较大的窗口尺寸增加复杂性:
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: 100%; height: 50px; background: blue; position: relative; } @media (min-width: 520px) { .changing__width__element { width: 50px; } }
<body> <div class="box"> <div class="changing__width__element"></div> </div> </body>
如果你不想走 CSS 路线,这可能是最简单的解决方案,不要使用screen.width
,使用window.innerWidth
,你可以在这里阅读更多关于差异的信息: what-is-the-difference-between -窗口内部宽度和屏幕宽度
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.