0

我是一名学生,正在学习如何编码。

我在尝试使用 Masonry 插件对齐我的块时遇到问题。

我正在尝试使每个块(.item)的高度和宽度相同,但是由于我使用的是百分比,因此我不确定如何正确执行。如果它是一个更固定的值,例如像素,那就更容易了。

我正在使用 jQuery 1.9.1,David DeSandro 的 Masonry,CSS 在 meyerweb 上重置。

的HTML:

<body>
    <div class="wrapper">
        <div class="gridSizer"></div>
        <!-- FIRST ROW -->
        <section class="item" style="background:limeGreen">Everything is 125px in height and width</section>
        <section class="item" style="background:green">&nbsp;</section>
        <section class="item" style="background:olive">&nbsp;</section>
        <section class="item h2" style="background:lime">Only this block is 250px in height (.h2 class), but the aqua coloured box is not being pushed down.</section>
        <!-- SECOND ROW -->
        <section class="item" style="background:blue">&nbsp;</section>
        <section class="item" style="background:navy">&nbsp;</section>
        <section class="item" style="background:teal">&nbsp;</section>
        <section class="item" style="background:aqua">&nbsp;</section>
        <!-- THIRD ROW -->
        <section class="item" style="background:magenta">&nbsp;</section>
        <section class="item w2 h2" style="background:hotPink">This block is 250px in height and width (.w2 and .h2 classes)</section>
        <section class="item" style="background:deepPink">&nbsp;</section>
        <section class="item w2" style="background:lightCoral">If the width is increased (.w2 class), elements are still pushed</section>
        <section class="item">No background color assigned to this block</section>
        <section class="item" style="background:violet">&nbsp;</section>
    </div>
</body>

CSS:

html, body {
    min-height: 100%;
}
.wrapper {
    position: relative;
    margin: 0 auto;
    width: 500px;
}
.wrapper:after { /*clearfix*/
    content:' ';
    display: block;
    clear: both;
}
/*
 * MASONRY STUFF
 */
 .gridSizer {
    width: 25%;
}
.item {
    width: 25%;
    min-height: 125px;
}
.item.w2 {
    width: 50%;
}

JavaScript/jQuery:

var $container = $('.wrapper');

$container.masonry({
    columnWidth: '.gridSizer',
    itemSelector: '.item'
});
$('.item').css('height', $('.item').width());
$('.item.h2').css('height', $('.item').width() * 2);

这是我的问题的 jsfiddle:http: //jsfiddle.net/em5cU/

将不胜感激我能得到的任何帮助。谢谢!

4

1 回答 1

2

在调整所有元素的大小后,您应该初始化砌体。

将您的 JavaScript 更改为:

var $container = $('.wrapper');

//these should come before call to masonry()
$('.item').css('height', $('.item').width());
$('.item.h2').css('height', $('.item').width() * 2);

$container.masonry({
    columnWidth: '.gridSizer',
    itemSelector: '.item'
});

演示

于 2013-08-09T01:59:43.383 回答