在我的特定div上实现视差效果的简单方法?

时间:2014-04-10 08:50:26

标签: javascript jquery html css parallax

我正在网上寻找教程和内容,但是我无法得到任何工作或者我想要的教程,我对javascript不是很熟悉。

我想在about-banner的背景上产生视差效果:

HTML:

<div class="about-banner">
    <div class="container">
        (Content doesn't really matter)
    </div>
</div>

CSS:

.about-banner {
    height: 500px;
    background-image: url(../images/about-banner.jpg);
    border-top: 20px solid #52cbf5;
    margin: 80px 0 0;
}

如何实现它的简单说明!

2 个答案:

答案 0 :(得分:1)

希望此链接能为您提供帮助http://codepen.io/keithclark/pen/JycFw。试试这个。 JS没有结束

答案 1 :(得分:0)

我为此创建了一个功能,它没有完美无缺,但你可以玩弄逻辑:

jQuery.fn.parallax = function(strength, multiplier) {
    if (typeof multiplier == 'undefined') multiplier = 1;
    var offset = parseInt($(this).data('offset'));
    var split = $(this).data('offset').split(/([^0-9])/);
    var unit = split[split.length - 2];
    if (!offset) offset = 0;
    if ($(window).scrollTop() + $(window).height() >= $(this).offset().top) {
        var newVal = (($(window).scrollTop() * strength / 2000 + offset) * multiplier).toFixed(2);
        $(this).css('background-position', 'center ' + newVal + unit);
        console.log($(this).attr('id') + ' ' + 'center ' + newVal + unit);
    }
}

为了使用它,你可以这样做:

$(window).scroll(function() {
    $('.about-banner').parallax(100, 2);
});

如果您希望从顶部以外的其他地方开始,可以添加data-offset="10px"或类似内容。