Jit*_*yas 46 javascript css jquery css3 jquery-mobile
如何使用javascript有条件地像CSS3媒体查询,方向?
例如,我可以编写具体的css
@media only screen and (width : 1024px) and (orientation : landscape) {
.selector1 { width:960px}
}
Run Code Online (Sandbox Code Playgroud)
现在我想只运行一些javascript,如果它匹配相同的条件
喜欢
@media only screen and (width : 1024px) and (orientation : landscape) {
A javascript code here
}
Run Code Online (Sandbox Code Playgroud)
我有一个外部JavaScript例如http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.min.js,它应该只在特定的屏幕大小和方向上运行
Emi*_*röm 57
这是使用javascript执行相同操作的更好方法:
https://github.com/paulirish/matchMedia.js/
测试移动设备媒体查询
if (matchMedia('only screen and (max-width: 480px)').matches) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
}
Run Code Online (Sandbox Code Playgroud)
测试横向方向
if (matchMedia('all and (orientation:landscape)').matches) {
// probably tablet in widescreen view
}
Run Code Online (Sandbox Code Playgroud)
mow*_*ker 12
...我想只在浏览器的最大宽度为1900px且最小宽度为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;
}
Run Code Online (Sandbox Code Playgroud)
Eri*_*ric 11
我可以想到一个快速的解决方案:有条件地将一些样式应用于一个不可见的div,并检查它们是否应用了javascript:
div#test { display: none }
@media only screen and (width : 1024px) and (orientation : landscape) {
div#test { background-color: white; }
}
Run Code Online (Sandbox Code Playgroud)
if(document.getElementById('test').style.backgroundColor == 'white')
mediaSelectorIsActive();
Run Code Online (Sandbox Code Playgroud)