【问题标题】:Select rendered picture element image in chrome在chrome中选择渲染的图片元素图像
【发布时间】:2014-12-18 04:57:06
【问题描述】:

我需要重新使用图片元素的渲染图像。有没有直接使用javascript访问chrome/opera渲染的图片文件路径的方法,而无需复制picturefill完成的逻辑。

<picture>
  <source media="(min-width: 800px)" srcset="head.jpg, head-2x.jpg 2x">
  <source media="(min-width: 450px)" srcset="head-small.jpg, head-small-2x.jpg 2x">
  <img src="head-fb.jpg" srcset="head-fb-2x.jpg 2x" >
</picture>

使用上面的示例,在宽度为 1200px 的视网膜桌面浏览器窗口上,支持图片的浏览器将呈现 head-2x.jpg。或者,如果我在宽度小于 450 像素且带有视网膜显示屏的智能手机上使用 chrome 浏览器,它将使用 head-fb-2x.jpg。如何直接访问这个动态渲染的图像?

有没有一种方法可以访问这个渲染的图像而不必自己解析源元素?

【问题讨论】:

    标签: javascript picturefill


    【解决方案1】:

    currentSrc 属性,只有在加载候选人时才会更新。函数可能看起来像这样:

    function getCurrentSrc(element, cb){
        var getSrc;
        if(!window.HTMLPictureElement){
            if(window.respimage){
                respimage({elements: [element]});
            } else if(window.picturefill){
                picturefill({elements: [element]});
            }
            cb(element.src);
            return;
        }
    
        getSrc = function(){
            element.removeEventListener('load', getSrc);
            element.removeEventListener('error', getSrc);
            cb(element.currentSrc);
        };
    
        element.addEventListener('load', getSrc);
        element.addEventListener('error', getSrc);
        if(element.complete){
            getSrc();
        }
    }
    

    注意:你必须传递img DOM 元素和一个回调函数。

    【讨论】:

    • 谢谢!然后我必须对跨浏览器支持进行进一步调整。
    • 想知道,你需要改变什么。
    • @jason 您需要进行哪些跨浏览器更改?
    • // 图片加载完成后为真。 // 缓存图像时,IE11 不会触发加载,因此我们自己触发加载事件。 if (this.complete) { $(this).load(); }
    • // 在 IE9 或 IE10 中,complete 为 false,并且不会触发 load。 // 重置图片源属性触发加载事件。 if (document.documentMode === 9 || document.documentMode === 10) { image.attr('src', $(image).attr('src')); }
    猜你喜欢
    • 2013-03-09
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2011-12-16
    • 1970-01-01
    相关资源
    最近更新 更多