
为何菜单栏下拉后top值不变,而修改后也不生效?
在希望菜单栏下拉至固定位置并保持不动时,修改其top值看似简单,但往往会遇到问题。例如,以下代码中,菜单栏的top值始终保持为260px,即使页面向下滚动超出其初始位置:
var sideBarRight = document.querySelector('.sideBar_right ul');
var sideBarRightTop = sideBarRight.offsetTop;
var currentTop = '';
document.body.onscroll = function() {
var docScrollH = document.documentElement.scrollTop;
if (docScrollH > sideBarRightTop ) {
sideBarRight.style.position = 'fixed';
sideBarRight.style.top = '75px';
}
else {
sideBarRight.style.position = 'absolute';
sideBarRight.style.top = currentTop;
}
}疑惑之处在于:
为了解答这些疑惑,让我们仔细分析代码行为:
当变量声明且未赋值时,其值为undefined。在第二个代码示例中,currenttop未赋值,因此为undefined。在if代码块中,sidebarright.style.top被设置为75px,但在else代码块中,currenttop用于将sidebarright.style.top设置为当前位置。由于currenttop为undefined,因此sidebarright.style.top被设为当前位置。
而在第一个代码示例中,currenttop被赋值为空字符串,因此其值不为undefined。即使直接运行else代码块,currenttop仍保留原始值260px。所以,sidebarright.style.top被设置为260px。
以上就是为何菜单栏下拉后top值不变,即使修改后仍失效?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号