繁体   English   中英

用Javascript检测屏幕的宽度

[英]Detecting a screen's width with Javascript

if(screen.availWidth > 850){
    //Do this
} else {
    //Do this   
}

这就是我现在所拥有的。 我现在的问题是,如果有人要放大页面,我希望更改宽度,因为这会影响页面的显示方式。

您是否应该更担心有人调整浏览器窗口的大小? 并非每个人都保持浏览器最大化。

去做这个:

if( (window.innerWidth || document.documentElement.clientWidth) > 850) {
    // do something
}
else {
    // do other thing
}

我相当确定这会将缩放考虑在内,但我从未测试过。

将事件处理程序绑定到window.onresize事件

window.onresize = function(event) {
    if (screen.availWidth > 850) { ... }
};

如果您使用jQuery:

$(window).resize(function(){
    if ($(window).width() > 850) { ... }
});

此外,如果要创建响应式设计,请考虑使用CSS媒体查询 如果用户缩放浏览器窗口或调整浏览器窗口的大小,这将自动适应页面;如果用户禁用了JavaScript,它也将起作用。

/* CSS */
@media (min-width: 850px) {
    /* style */
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM