
为何菜单栏下拉后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; }}
疑惑之处在于:
将currenttop赋值为空字符串后,它为什么仍等于260px?如果在不赋值currenttop的情况下运行代码,sidebarright.style.top为什么又会变成75px?这与变量类型null和undefined是否相关?
为了解答这些疑惑,让我们仔细分析代码行为:
当变量声明且未赋值时,其值为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值不变,即使修改后仍失效?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1631339.html
微信扫一扫
支付宝扫一扫