因此,每次调整窗口大小时,当屏幕大小低于520px时,我需要更改蓝色正方形元素宽度。蓝色方块应具有绿色方块方块width样式应以百分比为单位
没有什么能像我现在这样工作:(
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
,你可以在这里阅读更多关于区别的信息:窗口内部宽度和屏幕宽度之间的区别是什么
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。只需使用媒体查询,如果窗口的大小小于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>