我正在尝试基于客户端浏览器的innerWidth创建一些响应元素。
例如,如果innerWidth小于1300 is,我希望div的大小增加,否则我希望它保持它的初始CSS值。
我尝试了下面的代码,该代码主动跟踪客户端innerWidth大小,但在达到特定值时不更改元素。
实际上,我试图在某些断点上加入响应性元素。
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";
};发布于 2017-04-18 15:57:47
您应该为此使用CSS媒体查询,而不是JavaScript。
运行下面的片段,然后单击片段窗口右侧的“完整页面”链接。您将看到背景颜色从黄色变为绿色(假设您的屏幕至少有1300 is宽)。
/* 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>
https://stackoverflow.com/questions/43476871
复制相似问题