【问题标题】:Bind click toggle to image instead of whole div in Masonry将单击切换绑定到图像而不是 Masonry 中的整个 div
【发布时间】:2014-04-22 18:04:13
【问题描述】:

我正在使用 Masonry 来切换 div 的高度和宽度。我在扩展 div 内有链接,但我不知道如何制作它,以便仅在单击图像而不是 div 内的任何位置时切换高度/宽度。

jQuery:

var $container = $('.masonry').masonry({
    columnWidth: 145,
    itemSelector: '.item',
    "isFitWidth": true
});
$container.on('click', '.item-content', function(){
    $(this).parent('.item').toggleClass('is-expanded');
    $container.masonry();
});

内容循环(WordPress):

<div class="masonry">
    <?php while ($cpts->have_posts()) : $cpts->the_post();
        echo '<li class="item ';
        $cats = get_the_terms($post->ID, 'item_category');
        foreach($cats as $cat){
            echo 'ff-item-type-'.$cat->term_id.' '; 
        }
        echo '">';
        ?>
        <div class="item-content">
            <p class="filter-img" data-id="<?php echo $post->ID; ?>"><?php the_post_thumbnail(); ?></p>
            <?php echo wp_get_attachment_image(get_field('website_image'), array(135,135), false, array('class'=>'site-img')); ?>
            <h4><?php the_title(); ?></h4>
            <?php the_content(); ?>
        </div>
        </li>
    <? endwhile; ?>
</div>

【问题讨论】:

  • “整体”到底是什么意思?
  • 可以点击 div 中的任何位置,然后打开和关闭。我只希望 div 内的一个特定区域打开和关闭它。

标签: javascript jquery html jquery-masonry masonry


【解决方案1】:

尝试为 div 应用 pointer-events:none。引用 MDN:

元素永远不是鼠标事件的目标;但是,如果这些后代元素的指针事件设置为其他值,则鼠标事件可能会针对其后代元素。在这些情况下,鼠标事件将在事件捕获/冒泡阶段期间适当地触发此父元素上的事件侦听器。

更新

假设容器 div 具有 .masonry 类,请在您的 css 中添加以下内容

.masonry{
 pointer-events:none;
}

这样做不会触发以容器div为目标的点击事件,只有可点击的子元素会触发点击事件...

【讨论】:

  • 那行不通。你有什么例子吗?
  • 为了让这个问题成为一个完整的问题,您可能应该提到您需要将特定元素的 css 设置为 pointer-events: all。此外,当 div 中有链接时,这也无济于事。如果我将其设置为 pointer-events: all,则链接有效,但仍会关闭 div。
【解决方案2】:

我使用了这个而不是 JS 的 $container.on('click') 部分:

$('.item-content .filter-img img').on('click', function(){
    $(this).closest('.item').toggleClass('is-expanded');
    $container.masonry();
});  

这样它会在点击事件中使用正确的项目,然后将类添加到正确的 div 中。

【讨论】:

    猜你喜欢
    • 2016-03-02
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多