首页 > 解决方案 > 基于定义起点的滚动的不透明度

问题描述

我写了一个小 jQuery 插件,当该部分到达窗口顶部时开始降低该部分的不透明度。

现在我想在该起点添加一个偏移量,即当元素距离窗口顶部一半高度时,我想开始降低不透明度。

我在这里创建了一支笔: https ://codepen.io/cosminn/pen/bywpOe

您还可以查看以下代码:

(function ( $ ) {
    $.fn.hideScroll = function() {
        return this.each(function(){ //Required for inidivudal elements of the same type
            var elem = $(this),
                elementTop = elem.offset().top,
                elementHeight = elem.outerHeight(),
                opacity, scale;
            $(document).bind('scroll', function(){
                var areaHidden = $(window).scrollTop() - elementTop, // How much of the element is off-screen at the top
                    areaVisible = elementHeight - areaHidden,
                    limit = $(window).scrollTop() + (elementHeight / 2);
                if (elementTop <= limit) {
                    opacity = areaVisible / elementHeight; // Equivalent to how much percent of the element is visible
                }
                else opacity = 1; // Sometimes the opacity remains at 0.9XXX, so we turn it to 1 when element is in-view or off-screen at the bottom of window
                elem.css('opacity', opacity);
            });
        });
    };
}( jQuery ));

$(document).ready(function(){
  $('header').hideScroll();
  $('section').hideScroll();
});

我的问题在这里:

limit = $(window).scrollTop() + (elementHeight / 2);
if (elementTop <= limit)

感觉就像忽略$(window).scrollTop()之后添加到限制变量中的任何内容。

我不是真正的开发人员,所以我可能缺少一个明显的东西。

标签: javascriptjqueryscroll

解决方案


试想一下,元素从更下方开始,高度为一半,这意味着:

var elementHeight = elem.outerHeight()/2;
var elementTop = elem.offset().top + elementHeight;

你的新笔


推荐阅读