【问题标题】:HTML5/jQuery Cross-Browser Responsive ImagesHTML5/jQuery 跨浏览器响应式图片
【发布时间】:2012-09-07 10:40:31
【问题描述】:

我正在尝试设计一种方法来显示以跨浏览器兼容的方式响应调整大小的图像。使用 CSS3 媒体查询是行不通的,因为它们没有得到广泛的支持。然而,jQuery 让我能够利用 HTML5 中的“数据”属性。

这是我想出的。还有其他人有好主意吗?或者可以对这个想法提供任何调整?

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>HTML5/jQuery Responsive Images</title>
        <style>
            body { padding: 0; margin: 0; }
        </style>
        <script src="jquery-1.6.2.min.js" type="text/javascript"></script>
        <script>
        $(window).resize(setSize)
        $(document).ready(setSize);
        function setSize() {
            var bodywidth = $(document).width();
            var small_max = 600;
            var medium_max = 800;

            if (bodywidth > small_max && bodywidth <= medium_max) {
                $('img').each(function(){
                    $(this).attr('src',$(this).data('src-800px'));
                });
            } else if (bodywidth <= small_max ) {
                $('img').each(function(){
                    $(this).attr('src',$(this).data('src-600px'));
                });
            } else if (bodywidth > medium_max ) {
                $('img').each(function(){
                    $(this).attr('src',$(this).data('src'));
                });
            }
        }
        </script>
    </head>
    <body>
        <img data-src="image.jpg" data-src-600px="image-600px.jpg" data-src-800px="image-800px.jpg" alt="Responsive image" style="width: 100%;" />
    </body>
</html>

【问题讨论】:

  • 好吧,您可以通过以下方式将 if/then 测试减少一半:if (bodywidth&lt;=small_max) {...} else if (bodywidth&lt;=medium_max) {...} else {...}

标签: jquery html web responsive-design


【解决方案1】:

将 img 标签设置为 display:inline 将为您处理响应。

【讨论】:

    【解决方案2】:

    看看我在这方面发表的一系列博文:

    http://queryj.wordpress.com/2012/07/06/responsive-images-whats-the-problem-9-2/

    基本上:

    1. 在块中放置图像标签
    2. 通过添加基于 noscript 块的图像来逐步增强页面
    3. 在需要时使用媒体查询侦听器更改图像

    你需要几个 polyfills 来实现这项技术——一个能够读取 noscript 标签 textContent 属性,一个能够为 IE

    【讨论】: