我正在使用 bootstrap 构建一个 wordpress 网站,我想使用 masonry 在我的主页上创建一个特色作品部分,以显示我最近的 3 个投资组合元素的缩略图和标题。
我希望投资组合元素以看似随机的方式放置(类似于:http://studiosweep.com/),而不仅仅是有序的网格格式。我不知道如何为我的投资组合元素分配不同的宽度,因为它们只是通过 wordpress 循环在特色作品部分中生成的。
这是我的 HTML:
<section id="work">
<div class="container-fluid">
<div class="row">
<div class="col-sm-offset-6 col-sm-6 text-center">
<h1>Featured Work</h1>
</div>
</div>
<div class="row" id="ms-container">
<?php query_posts('posts_per_page=3&post_type=work'); ?>
<?php while ( have_posts() ) : the_post();
$thumbnail = get_field('thumbnail');
$medium = get_field('medium');
$size = "large";
?>
<div class="ms-item col-lg-6 col-md-6 col-sm-6 col-xs-12">
<figure>
<a href="<?php the_permalink(); ?>"><?php echo wp_get_attachment_image($thumbnail, $size); ?></a>
</figure>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<div class="clearfix"></div>
</div>
<?php endwhile; // end of the loop. ?>
<?php wp_reset_query();
</div>
<div class="clearfix"></div>
</div>
</section>
这是脚本:
<script type="text/javascript">
jQuery(window).load(function() {
// MASSONRY Without jquery
var container = document.querySelector('#ms-container');
var msnry = new Masonry( container, {
itemSelector: '.ms-item',
columnWidth: '.ms-item',
});
});
</script>
至于 CSS,我真的不知道如何分配不同的列宽,所以目前我只有这个:
.ms-item {
宽度:38.23%;
右边距:80px;
底部边距:70px;
}
任何帮助将不胜感激!
最佳答案
假设您有 3 个不同的列宽类:
.ms-item-width-1, .ms-item-width-2, .ms-item-width-3
一个可能的解决方案是将这 3 个类添加到您的 css 文件中,并在 .ms-item 类之后将其中一个类随机分配给您的容器。 Masonry 将提供您添加到该容器的最后一个类的宽度。例如:
<div class="ms-item <?php echo 'ms-item-width-' . (rand(0, 3) + 1); ?> col-lg-6 col-md-6 col-sm-6 col-xs-12">
<figure>
<a href="<?php the_permalink(); ?>"><?php echo wp_get_attachment_image($thumbnail, $size); ?></a>
</figure>
更新:要随机化而不获取重复值,您可以有一个数组 $widths = array(1,2,3);
然后打乱这个数组 shuffle($widths);
而不是调用随机函数,您将删除数组的元素并将其替换为以下代码:
<div class="ms-item <?php echo 'ms-item-width-' . array_shift($widths); ?> col-lg-6 col-md-6 col-sm-6 col-xs-12">
这将为这 3 个元素提供唯一的宽度。
关于php - Masonry、WordPress Loop 和 Bootstrap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36755206/