我们基于 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/