因此,当我每次调整窗口大小时,当我的屏幕尺寸低于 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/