简体   繁体   中英

variable image width/height based on screen size

I'm working on a touch panel web page (for my home automation) that is going to run on both the iPad and the iPhone. What I'm wondering about is the ability to dynamically set the size of my touch icons based on the screen size.

If I'm on the iPad, I need the icons to be 150px by 150px, but if I'm on the iPhone, I need the icons to be 75px by 75px.

Is there a way to dynamically set the image sizes using jQuery?

Look in the user agent string, and then set them accordingly.

I'd do it like...

JavaScript / jQuery

if (navigator.userAgent.match(/iPhone/)) {
   $('body').addClass('iphone');
} else if (navigator.userAgent.match(/iPad/)) {
   $('body').addClass('ipad');
}

If you are using jQuery only for this, you could cut down on some bloat by replacing those addClass() lines with...

var body = document.getElementsByTagName('body')[0];
body.className = body.className + ' iphone';

...or to make sure it always looks pretty in the source...

var body = document.getElementsByTagName('body')[0];
var bodyClasses = body.className.split(' ');
bodyClasses.push('iphone');
body.className = bodyClasses.join(' ');

Check it out .

CSS

.ipad #nav button {
   width: 150px;
   height: 150px;
}

.iphone #nav button {
   width: 75px;
   height: 75px;
}

This is assuming your buttons will scale by default in the browser - if you have two different images, you could change the background-image CSS property.

您可以检查字符串iPadiPhone是否出现在navigator.userAgent ,并相应地设置图像URL。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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