根据屏幕宽度加载缩略图图像

时间:2013-07-11 14:16:27

标签: javascript html css

我希望能够根据页面的宽度将大量缩略图加载到页面上。加载的图像数量取决于页面的宽度。

图像(100 x 100)将加载,使它们并排,并占据整个屏幕宽度。

实现这一目标的最佳方式是什么?

提前致谢

这是我到目前为止所提出的: -                     

<script src="Scripts/jquery-1.9.0.min.js" type="text/javascript"></script>

<style type="text/css">

    #dv_frame {
        width: 100%;
        /*border: 1px solid #cccccc;*/
        text-align: center;
        height: 110px;
        position: relative;

    }

    #dv_images {
        /*border: solid 1px blue;*/
        height: 100px;

        margin: auto;

    }

    .myImage{
        width: 100px;
        height: 100px;
        border: solid 1px red;
        float: left;
        margin-right: 5px;
        margin-left: 5px;
    }



</style>


<script type="text/javascript">

    $(document).ready(function () {

        var container = $("#dv_frame")
        var tWidth = 0
        var width = container.width()

        for (c = 0; c < 100; c++) {
            tWidth = tWidth + 110
            if (tWidth > (width - 10)) {
                $("#dv_images").css("width", (tWidth - 80))
                break;
            }
            addSquare()
        }

        function addSquare() {
            $("#dv_images").append("<div class='myImage'></div>")
        }

    });

</script>

   </head>

 <body>
<div id="dv_frame"><div id="dv_images"></div></div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我不是每次都添加图像和检查宽度,而是从头开始计算所需的图像数量。将它们添加到不在DOM中的虚拟div中,然后最终将其附加到容器中(为了提高速度和效率)。

var $container = $("#dv_frame"),
    imageWidth = 110, // including margin & padding
    imagesNeeded = Math.floor($container.width() / imageWidth), // rounded down, width/imageWidth
    i, // iterator
    $foo = $('<div></div>'); // empty container div

for(i = 0; i < imagesNeeded; i++) {
    // appending to our empty container div
    $foo.append("<div class='myImage'></div>");
}

// then appending the contents of our container div to the DOM.
// this is quicker and more efficient than doing lots of appends to the DOM in a loop.
$("#dv_images").append($foo.contents());

示例:http://jsfiddle.net/lukemartin/d8WNy/

相关问题