繁体   English   中英

如何像 CSS3 媒体查询、方向一样有条件地使用 javascript?

[英]How to use javascript conditionally like CSS3 media queries, orientation?

如何像 CSS3 媒体查询、方向一样有条件地使用 javascript?

例如,我可以为特定的对象编写 css

@media only screen and (width : 1024px) and (orientation : landscape) {

.selector1 { width:960px}

}

现在我只想运行一些符合相同条件的 javascript

喜欢

@media only screen and (width : 1024px) and (orientation : landscape) {

A javascript code here

}

我有一个外部 javascript,例如http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.min.js ,它应该只在特定的屏幕尺寸和方向上运行

您可以使用window.matchMedia()

测试移动设备媒体查询

if (matchMedia('only screen and (max-width: 480px)').matches) {
  // smartphone/iphone... maybe run some small-screen related dom scripting?
}

测试横向

if (matchMedia('all and (orientation:landscape)').matches) {
  // probably tablet in widescreen view
}

当前在所有现代浏览器中都受支持(更多详细信息

旧浏览器的 Polyfill: https : //github.com/paulirish/matchMedia.js/

...我只想在浏览器的最大宽度为 1900 像素且最小宽度为 768 时运行 javascript

编辑:实际上,那都是错误的。 如果您使用的是移动设备,请使用:

function doStuff(){
    landscape = window.orientation? window.orientation=='landscape' : true;

    if(landscape && window.innerWidth<1900 && window.innerWidth > 768){
        //code here
    }
}
window.onload=window.onresize=doStuff;
if(window.onorientationchange){
    window.onorientationchange=doStuff;
}

我可以想到一个快速的解决方案:有条件地将一些样式应用到一个不可见的 div,并检查它们是否与 javascript 一起应用:

div#test { display: none }
@media only screen and (width : 1024px) and (orientation : landscape) {
    div#test { background-color: white; }
}
if(document.getElementById('test').style.backgroundColor == 'white')
    mediaSelectorIsActive();

可能值得一提的是,您可能希望像这样挂钩orientationchange事件:

$('body').bind('orientationchange', function(){
    // check orientation, update styles accordingly
});

我知道移动 Safari 会触发此事件,您必须检查其他浏览器。

您可以将媒体查询重写为 javascript 表达式:

function sizehandler(evt) {
    ...
}

function orientationhandler(evt){  

  // For FF3.6+  
  if (!evt.gamma && !evt.beta) {  
    evt.gamma = -(evt.x * (180 / Math.PI));  
    evt.beta = -(evt.y * (180 / Math.PI));  
  }  

  // use evt.gamma, evt.beta, and evt.alpha   
  // according to dev.w3.org/geo/api/spec-source-orientation  

  ...
}  

window.addEventListener('deviceorientation', orientationhandler, false);
window.addEventListener('MozOrientation', orientationhandler, false);
window.addEventListener('load', orientationhandler, false); 
window.addEventListener('resize', sizehandler, false); 
window.addEventListener('load', sizehandler, false); 

我发现的最简单的方法是获取我们页面的宽度; 然后有条件地使用它。

 var x = document.documentElement.clientWidth; if (x < 992) { document.body.style.backgroundColor = "yellow"; }

暂无
暂无

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

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