我编写了一个小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()后在 limit 变量中添加的内容一样。
我不是真正的开发人员,所以可能有明显的东西我想念。
答案 0 :(得分:0)
试想一下,该元素从更低的位置开始高度为一半,这意味着:
var elementHeight = elem.outerHeight()/2;
var elementTop = elem.offset().top + elementHeight;
您的New Pen。