【发布时间】:2014-08-21 12:03:56
【问题描述】:
我一直在使用以下代码来替换我的响应式图片:
//HTML:
<img id="testimage" onLoad="minWidth32('test_image')" src="testimage_small.jpg">
//JavaScript:
var screencheck = window.matchMedia("(min-width: 32em)");
function minWidth32(imageName) {
if (screencheck.matches) {
currentImage = document.images[imageName];
currentImage.src = imageName + "_large.jpg";
}
}
(编辑)新的精简版 JavaScript:
var screencheck = window.matchMedia("(min-width: 32em)");
function minWidth32(imageID) {
if (screencheck.matches) {
document.getElementById(imageID).src = imageID + "_large.jpg";
}
}
我真的很喜欢“图像 ID + 文本字符串”的图像更改方法。它允许单个脚本(每个媒体查询)根据需要运行尽可能多的图像。许多响应式图像脚本/插件/库都涉及到这一点。很多。标记。
但是这个特定的脚本只能在某种程度上起作用:
1.) 最初设计用于“onMouseOver”翻转效果,该脚本需要一个事件监听器。这对于响应式图像脚本来说并不理想,因为在“onLoad”事件结束很久之后,浏览器会调整大小并且移动设备会改变方向。
2.) 此脚本只能更改非空 src 属性(在上例中从“test_image_small.jpg”更改为“test_image_large.jpg”)。这意味着两个图像仍在加载,浪费带宽并使布局令人讨厌地跳来跳去。我宁愿填写一个空的 src 属性。
所以基本上我需要 - 并且无法弄清楚 - 是这样的:
//if (screencheck.matches &&
//item is an image tag &&
//item has empty src attribute &&
//item has non-empty ID attribute) {
//set item src attribute = item ID attribute + a text string
//}
【问题讨论】:
标签: javascript responsive-design media-queries matchmedia