0

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

图像 (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>
4

1 回答 1

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/

于 2013-07-11T14:45:17.260 回答