我正在尝试根据客户端浏览器的innerWidth 创建一些响应式元素。
例如,如果 insideWidth 小于 1300px,我希望 div 增大尺寸,否则我希望它保持其初始 CSS 值。
我尝试了下面的代码,该代码主动跟踪客户端 insideWidth 大小,但在达到特定值时不会更改元素。
我本质上是在尝试在某些断点处合并响应式元素。
function clientWidth(){
// Get the dimensions of the viewport
var width = window.innerWidth;
console.log(width);
};
var widthResult = clientWidth();
window.onresize = clientWidth;
var row1_col_3 = document.getElementById('row1_col_3');
if(widthResult < 1300){
row1_col_3.style.width = "450px";
} else{
row1_col_3.style.width = "300px";
};
最佳答案
您应该使用 CSS Media Queries 为此,而不是 JavaScript。
运行下面的代码片段,然后单击代码片段窗口右侧顶部的“完整页面”链接。您将看到背景颜色从黄色变为绿色(假设您的屏幕宽度至少为 1300 像素)。
/* Default style */
div {
background-color:yellow;
width:250px;
}
/* Style for when viewport is at least 1300px wide */
@media screen and (min-width: 1300px) {
div {
background-color:green;
width:750px;
}
}
<div>Hello</div>
关于javascript - 如果 innerWidth < 1300,则根据 javascript window.resize 更改 div 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43476871/