视差滚动工作在1张图片上但不在其他

时间:2016-05-21 14:15:17

标签: jquery html css

我正致力于为我的2张背景图像提供视差效果,它正在处理第一张图片但不在第二张图片上...代码如下

jquery:

$(document).ready(function() {
$('section[data-type="background"]').each(function() {

        var $bgobj = $(this); // assigning the object

        $(window).scroll(function() {

            // scroll the background at var speed
            // the yPos is a negative value because we're scrolling it UP!

            var yPos = -($window.scrollTop() / $bgobj.data('speed'));

            // Put together our final background position
            var coords = '50% '+ yPos + 'px';

            // Move the background
            $bgobj.css({ backgroundPosition: coords });

        }); // end window scroll

    });

});

HTML: -

<section class="parallax" data-type="background" data-speed="5">
        <h2>Check out this cool parallax scrolling effect. Use these ribbons to display calls to action mid-page.</h2>
        <button class="btn btn-lg btn-info">PARALLAX</button>

    </section>

CSS: -

.parallax {
    height:35em;
    background: url('https://images.unsplash.com/photo-1463123081488-789f998ac9c4?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=6d1a6d1c5a7eb63d0c411b1d019f0b30');
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
}

.parallax h2 {
    color: white;
    text-align: center;
    padding: 1em;
    padding-top: 5em;
}

.parallax button {
    display: block;
    margin: 2em auto;
}

奇怪的是,第二张图片根本没有显示,只有当我删除数据速度属性但后来视差不起作用时才会显示...我感到困惑,所以请协助..

2 个答案:

答案 0 :(得分:2)

您正在使用$ window.scrollTop(),当您向下滚动页面并将其设置为相对于图像容器顶部时,它会变大。好像你需要先从文档顶部减去元素位置:

$(document).ready(function() {
$('section[data-type="background"]').each(function() {

    var $bgobj = $(this); // assigning the object

    $(window).scroll(function() {

        // scroll the background at var speed
        // the yPos is a negative value because we're scrolling it UP!

        var yOffset = $bgobj.offset().top;
        var yPos = -(($window.scrollTop() - yOffset) / $bgobj.data('speed'));

        // Put together our final background position
        var coords = '50% '+ yPos + 'px';

        // Move the background
        $bgobj.css({ backgroundPosition: coords });

    }); // end window scroll

});

});

您的第一张图片可能正常工作,因为它位于页面顶部,因此偏移无关紧要?

答案 1 :(得分:0)

试试这个

<?php 
if($termid->parent > 10) {
    $args = array(
        'orderby'       => 'name', 
        'order'         => 'ASC',
        'hide_empty'    => false, 
        'child_of'      => $termid->parent,
    ); 

$categories = get_the_terms( get_the_ID(), 'product_cat', $args ); 
if ( $categories && ! is_wp_error( $category ) ) : 
    foreach($categories as $category) :
      $children = get_categories( array ('taxonomy' => 'product_cat', 'parent' => $category->term_id ));
      if ( count($children) == 0 ) { ?>
      <span class="product-sub-cats"><?php echo $category->name; ?></span>
      <?php }
    endforeach;
endif;
}
?>