jQuery 移动 : Conditional Image Sizes (Phone/Tablet)

标签 jquery iphone jquery-mobile tablet

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

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

例如,

myImage_large.png
myImage_small.png

有没有办法使用数据标签或其他 jQuery 移动方法在 img 标签中指定在较小的设备上应使用较小的图像。

最佳答案

如果您将 block 元素与background-image一起使用,您可以在CSS中指定图像的来源,这允许您创建仅加载正确图像的媒体查询。大多数移动浏览器都支持媒体查询,因此最好从默认的高分辨率开始,然后使用媒体查询将 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" />

关于jQuery 移动 : Conditional Image Sizes (Phone/Tablet),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8857688/

相关文章:

javascript - 在 JQuery 中设置 Src 属性的正确方法是什么?

带有参数的 Javascript 结构函数

ios - UITableViewCONtroller 中的快速多个单元格子类

javascript - PhoneGap Javascript 除了在索引文件中以外不工作

javascript - 在动态创建单选按钮方面需要帮助

javascript - Jquery Mobile - $.mobile.changepage 不加载外部 .JS 文件

jquery - jQuery 中的第 N 个类型通配符?

javascript - 如何通过传递参数属性来更改 polymer 元素模板

iphone - 使用 NSDictionary 内容创建 NSManagedObject

ios - 动画 TabBar 颜色变化