我正在编写一个脚本,它使用 jQuery 的data()src
函数和 HTML5 数据属性来根据媒体查询动态切换图像的属性。这背后的想法是默认提供低保真图像(针对移动设备进行了优化),并为更大的屏幕提供高保真图像。(这不一定限于图像。)该脚本在 Chrome/Opera/Safari/iOS 中 100% 有效,但在 FF 和 IE 中不完全有效。
<img src="ex1_lo-res.png" data-websrc="ex2_hi-res.png" alt="example">
<img src="ex2_lo-res.png" data-websrc="ex2_hi-res.png" alt="example">
一个实际使用的例子是responsetheme.com,在 480px 宽以上的图像应该是粉红色的,而在 480px 宽的图像应该是黄色的。我知道FF 和 IE 都支持 和 —— 我在没有该功能的情况下测试了data()
它们。所以我认为这个问题与触发器或or函数有关。关于我缺少什么的任何想法?Modernizr.mq
resize()
each()
resize()
jQuery(document).ready(function($) {
/* get elements that have a data-websrc attribute */
$websrc = $('[data-websrc]');
$websrc.each(function() {
/*
Set data-osrc equal to element's original src value.
This allows us the ability to access the original src
(even after we replace the attribute).
*/
var $this = $(this);
$this.data('osrc', $this.attr('src'));
});
$(window).resize(function() {
/*
Check breakpoint.
(Modernizr.mq checks the media query and returns boolean.)
*/
airsrcWEB = Modernizr.mq('screen and (min-width:480px)');
/*
Replace src with data-websrc (if above breakpoint).
Otherwise fallback to data-osrc (original src).
*/
$websrc.each(function() {
var $this = $(this);
var src = ( window.airsrcWEB ) ? $this.data('websrc') : $this.data('osrc');
$this.attr('src', src);
});
}).resize(); // trigger resize handlers
});
此外,我不确定我是否以最有效的方式拥有功能,就其内部而言,所以我也想听听任何加快速度的提示。=)
更新1:我也尝试过这样的三元,但仍然是同样的问题:
var src = ( airsrcWEB ) ? $this.data('websrc') : $this.data('osrc');
更新 2:我发现了 FF 的问题。显然,FF6 窗口的大小不会调整到低于 556px 宽。我用上面的断点测试了脚本,并且开关工作了。(即使是在 FF6 中 mediaqueri.es 上的示例也不会缩小到 556px 以下。)