在我的网页上,我使用Javascript来响应地更改页面元素的布局。最初,我在调整大小的事件侦听器中使用带有if (window.innerWidth > 768)
的脚本来像CSS媒体查询一样工作,并且运行流畅。在768像素阈值范围内调整大小时,布局按照预期做出了响应。
然后,当视口宽度大于高度时,我决定将if语句更改为if (window.innerWidth > window.innerHeight)
来更改页面元素的布局,反之亦然。但是,每当我调整页面大小以触发布局更改时,页面就会冻结并变成黑色。但是,当我刷新页面时,它在调整大小的布局后加载得很好。似乎只有手动更改窗口大小才会导致页面冻结。
此行为背后的原因是什么?我的代码真的效率低吗?
这是我的调整大小的侦听器功能:
function resizeListener(){
//selectors
let sections = [].slice.call(document.getElementsByTagName('section'));
let items = [].slice.call(document.getElementsByClassName('section-item'));
let heads = [].slice.call(document.getElementsByClassName('header'));
let descs = [].slice.call(document.getElementsByClassName('description'));
let windowWidth = window.innerWidth;
let windowHeight = window.innerHeight;
//window width > height
if (windowWidth > windowHeight){
//grid layout
sections.forEach((x)=>{
x.style.display = "grid";
});
items.forEach((x)=>{
x.style.width = "auto";
x.style.maxWidth = "none";
x.style.height = "auto";
x.style.margin = "0";
let img = x.childNodes[0];
img.style.width = "auto";
img.style.height = "100%";
});
//if width big enough, let window height decide styling
if (windowWidth > windowHeight * 1.6){
sections.forEach((x)=>{
x.style.height = "100vh";
x.style.width = "160vh";
});
}
//else let window width decide styling
else {
sections.forEach((x)=>{
x.style.height = "62.5vw"
x.style.width = "100vw";
});
}
//style text according to height
let headRatio = 0.032;
let descRatio = 0.021;
let lineRatio = 0.053;
heads.forEach((x)=>{
x.style.fontSize = (x.parentNode.offsetHeight * headRatio) + 'px';
});
descs.forEach((x)=>{
let height = x.parentNode.offsetHeight;
x.style.fontSize = (height * descRatio) + 'px';
x.style.lineHeight = (height * lineRatio) + 'px';
});
}
//window height > width
else {
sections.forEach((x)=>{
x.style.display = "flex";
x.style.height = "auto";
x.style.width = "100vw";
});
items.forEach((x)=>{
x.style.width = "300px";
x.style.maxWidth = "90%";
x.style.height = "auto";
x.style.margin = "10px";
let img = x.childNodes[0];
img.style.width = "100%";
img.style.height = "auto";
});
heads.forEach((x)=>{
x.style.fontSize = "24px";
});
descs.forEach((x)=>{
x.style.fontSize = "14px";
x.style.lineHeight = "28px";
});
}
}