jQuery Mobile:条件图像大小(手机/平板电脑)

时间:2012-01-13 21:49:17

标签: jquery iphone jquery-mobile tablet

我们基于jQuery Mobile的网站将被大屏幕平板电脑和手机使用。

在手机上使用时,我们希望将一些较小的图像缩小。

例如,

myImage_large.png
myImage_small.png

是否有办法使用数据标记或其他jQuery-mobile方法在img标记中指定在较小的设备上应使用较小的图像。

3 个答案:

答案 0 :(得分:4)

如果您使用带有background-image的块元素,则可以在CSS中指定图像的来源,这样您就可以创建仅加载正确图像的媒体查询。大多数移动浏览器都支持媒体查询,因此最好先将hi-res作为默认值,然后使用媒体查询将background-image源更改为低分辨率:

/*set source for hi-res images here (default)*/
#image-1 {
    position : relative;
    width    : ...px;
    height   : ...px;
    display  : inline-block;
    background-image : url(/images/this-image-hi.jpg);
} 
@media all and (max-width:480px) {
    /*set source for lo-res images here*/
    #image-1 {
        background-image : url(/images/this-image-lo.jpg);
    }
}

然后您的图片标记将更改为:

<div id="image-1"></div>

您还可以将所有图像源属性设置为空白像素,然后让JavaScript函数在document.ready上更改其来源:

$(function () {
    if (HI-RES) {
        $('img[data-src-hi]').each(function (index, element) {
            this.src = $(this).attr('data-src-hi');
        });
    } else {
        //output lo-res images
        $('img[data-src-lo]').each(function (index, element) {
            this.src = $(this).attr('data-src-lo');
        });
    }
});

这要求您的图片代码如下所示:

<img src="/images/blank-pixel.png" width="xx" height="xx" data-src-hi="/images/this-image-hi.jpg" data-src-lo="/images/this-image-lo.jpg" />

答案 1 :(得分:0)

响应式图片[https://github.com/filamentgroup/Responsive-Images]看起来可能非常接近您所寻找的内容。它不一定是jQuery / mobile特定的,但它会根据屏幕分辨率加载不同的大小。

答案 2 :(得分:0)

如果你真的希望它响应你必须在平板电脑中添加调整大小的事件,旋转设备的智能手机将调整大小,所以你应该使用调整大小事件来触发这里的更改就是我所做的一个例子:

function responsiveImage(hi_res) {
    if (hi_res) {
        $('img[data-src-hi]').each(function (index, element) {
            $(this).attr("src",$(this).attr('data-src-hi'));
        });
    } else {
        //output lo-res images
        $('img[data-src-lo]').each(function (index, element) {
            $(this).attr("src",$(this).attr('data-src-lo'));
        });
    }  
}



$(function(){
    var hi_res = false;
    var max_width = 480;

    if($(window).width()>max_width){
        hi_res = true;
    }
    responsiveImage(hi_res);

    $(window).resize(function() {
        if($(window).width()>max_width){
            hi_res = true;
        }else{
            hi_res = false;
        }
        responsiveImage(hi_res);
    });

});

使用此html

<img data-src-hi="/media/img/large_img.png" data-src-lo="/media/img/small_img.png" src="" />