我正在使用bootstrap和jquery创建一个网站,我正在为桌面/移动设备进行测试。通过javascript,我不得不修改DOM中的一些元素,否则布局会太混乱。将我的Lumia 735(WindowsPhone 8.1 GDR1)与IE11一起使用时,我注意到浏览器并没有真正"感知"屏幕旋转。为此,我在页面中添加了一个简单的代码(如下所示),并尝试以两个方向多次加载和重新加载页面,但仅显示纵向尺寸
<div id="screenDimensions"></div>
<script>
/*set of parameters*/
var screenHeight =
window.screen.height;
var screenWidth =
window.screen.width;
/*creation of the function that shows you the screen dimensions*/
function writeDimensions(){
/*change of the values in the parameters*/
screenHeight =
window.screen.height;
screenWidth =
window.screen.width;
/*change of the content of the div screenDimensions*/
document.getElementById('screenDimensions').innerHTML=
("<strong>width: "
+screenWidth
+", height: "
+screenHeight
+"</strong>"
);
}
/*execute the function once when the page is ready*/
$(document).ready(function(){
writeDimensions();
})
/*and do it again when you sense a resize in the browser dimensions*/
$(window).resize(function(){
writeDimensions();
})
</script>
我的问题是:有没有办法让浏览器(在移动设备/平板电脑上)感知旋转?否则,有没有办法优化小屏幕的布局?
编辑。经过进一步的测试,我发现CSS可以感知旋转(请参阅以下代码),但是Javascript(如上所述也已更新)仍然无法正常工作。
在我添加的页脚中(这样,您将始终有一个彩色条带,当您旋转屏幕时,该条带应更改其颜色)
<div id="testdiv">
<strong>Color case</strong>
</div>
使用以下 CSS 规则:
#testdiv{
background-color:#3399FF; //blue, default colour
}
@media only screen and (max-width:1080px){
#testdiv{
background-color:#99FF99; //light green
}
}
@media only screen and (max-width:768px){
#testdiv{
background-color:#CC00CC; //purple
}
}
@media only screen and (max-width:600px){ //random value
#testdiv{
background-color:#00CC00; //green
}
}
@media only screen and (max-width:450px){ //random value
#testdiv{
background-color:#996633; //brown
}
}
问题和以前一样,我补充一点:在桌面上,上面的javascript可以工作,在移动号码上。CSS应该在它上面工作。为什么?
尝试跟随而不是 $(window).resize(function(){}
var mql = window.matchMedia("(orientation: portrait)");
// If there are matches, we're in portrait
if(mql.matches) {
// Portrait orientation
} else {
// Landscape orientation
}
// Add a media query change listener
mql.addListener(function(m) {
if(m.matches) {
// Changed to portrait
}
else {
// Changed to landscape
}
});