Phonegap - reliable page width detection?

主宰稳场 提交于 2019-12-24 00:58:40

问题


Can anybody recommend a good way to detect screen width on a HTML5 Android App built in Phonegap?

Our page is reasonably fluid - but I need to switch logo's/footer graphics for smaller screens - so I inject a stylesheet for smaller versions - seems to work fine in general, some phones (HTC Wildfire)seem to think they are 320px width when they are only 240 so I'm struggling!

This is my current detection code - any suggestions would be really helpful!

Cheers Paul

 $(document).ready(function() {
 var pageWidth = $(window).width();
 var sizeSelected = "chilliAppBeta";
 alert(pageWidth);adjustCSS();

 function adjustCSS(){
 if (pageWidth >= 0) { if(pageWidth < 300) {alert("smallscreen"); applyChilliCSS();}  }
 if (pageWidth >= 300) { sizeSelected = "chilliAppBeta" }
 }

 function applyChilliCSS() {
 var chilliStyleSheet =$('<link href="CSS/chilliAppBetaSmall.css" rel="stylesheet"        class="chilliLink" type="text/css"/>');

 $('head').append(chilliStyleSheet);

 }
 });

回答1:


You don't need JavaScript to add additional rules based on your screen dimensions, you can use CSS3 Media Queries instead like:

.smallScreenContent{
display: none;
}
@media (max-width:400px){ //the following rules will only be used for screens up to 400px width
.smallScreenContent{
display: block;
}
}​

See this link for specifications and this fiddle (resize the result) for a working demo.




回答2:


The only way I found to correctly detect the window size is to put a timeout of a couple of seconds before to let the canvas fit the screen. At launch it shows up on the top left corner and only spreads to fit the screen after a short while.




回答3:


Use

$(window).width() // For width 
$(window).height() // For Height

Alternatively you could check the width of a data-role="page" element to find the device-width (since it's set to 100% of the device-width):

var deviceWidth = 0;
$(window).bind('resize', function () {
    deviceWidth = $('[data-role="page"]').first().width());
}).trigger('resize');​​​


来源:https://stackoverflow.com/questions/9666870/phonegap-reliable-page-width-detection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!