开发者

media queries image file name change on screen size

I've been looking at using media queries on a site but bolt at the idea of downloading a huge file only for it take ages to download on a iphone over 3G.

Is it possible using jquery to alter a filename (ie. add -iphone to background.jpg to make background-iphone.jpg) when the site is viewed on an iphone / netbook / ipad perhaps using media queries in there too.

In my head it seems like it should be possible. It'd be great if anyone out there could work it out too :-D

thanks in advance

stu

I've found this code for finding screen sizes

$(document).ready(function() {

if (开发者_开发技巧(screen.width>=1024) && (screen.height>=768)) {
alert('Screen size: 1024x600 or larger');
$("link[rel=stylesheet]:not(:first)").attr({href : "detect1024.css"});
}
else  {
alert('Screen size: less than 1024x768, 800x600 maybe?');
$("link[rel=stylesheet]:not(:first)").attr({href : "detect800.css"});
}
});

and I've found this script which I think adds text to file

$('.rollover').hover(
        function(){ // Change the input image's source when we "roll on"
            var t = $(this);
            t.attr('src',t.attr('src').replace(/([^.]*)\.(.*)/, "$1-over.$2"));
        },
        function(){ 
            var t= $(this);
            t.attr('src',t.attr('src').replace('-mobile',''));
        }
 );

any ideas how I can combine the two ??

maybe something like this -

$(document).ready(function() {

if ((screen.width>=1024) && (screen.height>=768)) {
var t= $(this);
t.atter('src',t.attr('src').replace('-mobile',''))
}
);

but don't know how to fix syntax errors

Or maybe this - still has ending syntax error though

$(document).ready(function() {

if ((screen.width>=1024) && (screen.height>=768)) {

   var re = new RegExp("(.+)_hover\\.(gif|png|jpg)", "g");
   return filename.replace(re, "$1.$2");
}


It is possible, and also not too hard to achieve. But for simplicity's sake, why not use something like:

$(document).ready(function() {

  if ((screen.width<=960) && (screen.height<=640)) {

    $("#someid").addClass("iphone");

  }

});

That way, when the browser detects a resolution equal to or lower than 960x640 (iPhone 4 resolution), it will automatically add a class of "iphone" to any element you specify. This could be the body tag, a custom ID and so on.

All you need to do then is specify a different background image for the class "iphone".

Simple.


Or for a solution allowing you to use image tags, see below:

$(document).ready(function() {

  if ((screen.width<=960) && (screen.height<=640)) {

    $("img").attr("src", $("img").attr("src").replace(/([^.]*)\.(.*)/, "$1-iphone.$2"));

  }

});

That should do the trick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜