javascript - 基于定义起点的滚动的不透明度
问题描述
我写了一个小 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()之后添加到限制变量中的任何内容。
我不是真正的开发人员,所以我可能缺少一个明显的东西。
解决方案
试想一下,元素从更下方开始,高度为一半,这意味着:
var elementHeight = elem.outerHeight()/2;
var elementTop = elem.offset().top + elementHeight;
你的新笔。
推荐阅读
- ios - 是否可以以编程方式更新情节提要
- spring-boot - 使用在 tomcat 上运行的多个 Web 应用程序将 Spring Boot 中的应用程序配置文件外部化
- php - amphp:循环中的承诺
- javascript - 如何实时检查多个输入的值?
- powerbi - 在用户加载 PowerBI 站点之前,嵌入 URL 不会出现在 IFRAME 中
- c# - 重新加载文件并保存最后一行位置
- python - Python:将JPG图像添加到folium中的弹出窗口
- g++ - QEMU可以用g++编译吗?
- react-native - 使用 Expo 计步器时无法通过步骤
- windows-subsystem-for-linux - WSL 中的 Geckodriver 卡在“交互式”的 readyState 中