javascript - 如何根据位置更改粘性向上箭头按钮的属性?
问题描述
我的网页有一个粘性向上箭头图像,如下所示:
HTML:
<a href = "#navbar-scroll"><img src = "images/sticky-btn-light.png" id = "myBtn" alt = "sticky-up-button"></a>
和 CSS:
#myBtn {
visibility: hidden;
position: fixed;
bottom: 50px;
right: 30px;
z-index: 99;
cursor: pointer;
padding: 15px;
border-radius: 10px;
width: 5%;
opacity: 0.5 ;
}
该按钮在用户向下滚动时消失,当用户根据此JS代码向上滚动时出现。
window.onscroll = function(e) {
console.log(this.oldScroll > this.scrollY);
if((this.scrollY == 0) || (this.oldScroll < this.scrollY) ){
document.getElementById('myBtn').style.visibility = 'hidden';
}
else if(this.oldScroll > this.scrollY){
document.getElementById('myBtn').style.visibility = 'visible';
}
this.oldScroll = this.scrollY;
}
现在,我想根据它在屏幕上的变化位置来改变按钮的颜色。当我滚动页面时,粘性按钮将位于不同的部分,如下所示。 如果粘性按钮在 A 部分,它应该是红色的。如果它在 B 部分,它应该是蓝色的。请注意,移动的是页面,而不是按钮。按钮处于固定位置。
为此,我需要粘性按钮在任何给定时刻重叠的部分的 ID。有没有办法通过 JavaScript 获取这些信息?
PS:我已经调整了细节以使事情更加清晰。这是正在移动的页面。那么,如果我使用Element.getBoundingClientRect()
for #myBtn
,无论我在页面上滚动到哪里,我都不会得到相同的 top/y 值吗?
解决方案
在这里,我做了一个示例供您测试和实现。
getBoundingClientRect
即使位置固定,这也有助于理解
var arrow= document.getElementById('myBtn');
window.onscroll = function(e) {
var arrowBound = arrow.getBoundingClientRect();
var divs = document.querySelectorAll(".container > div");
divs.forEach(function(item){
var divBound = item.getBoundingClientRect();
var color= item.getAttribute("arrowColor");
if ( arrowBound.bottom > divBound.top && arrowBound.top < divBound.bottom )
{
arrow.style.borderTopColor = color
}
})
}
#myBtn {
position: fixed;
top: 10px;
left:270px;
z-index: 99;
cursor: pointer;
width: 0;
height: 0;
border-left: 20px solid transparent;
border-right: 20px solid transparent;
border-top: 20px solid #f00;
}
.container{
width:300px;
height:800px;
z-index: 81;
}
.container > div {
width:300px;
height:100px;
border:1px solid black;
}
<div class="container">
<a id = "myBtn" href = "#navbar-scroll"></a>
<div arrowColor="red"> box red </div>
<div arrowColor="blue"> box blue </div>
<div arrowColor="green"> box green </div>
</div>
推荐阅读
- r - 使用 R,如何使用 dplyr 的超前和滞后函数正确地从 POSIXct 变量中减去一秒?
- php - HttpOpenRequest () Wininet c++ e PHP
- javascript - 使用firestore登录时如何在本机反应中使用实时数据库?
- python - 调用类时局部变量引用错误
- python - 如何将字符串格式的日期转换为python pandas中的子可设置值
- flutter - 包含颤振中的 int 函数
- powershell-4.0 - 尝试提取日志文件中的最新错误并创建 custom.txt 输出
- c# - Visual Studio C#:是否可以在创建之前自动格式化控件的属性名称?
- azure-webjobs - Azure WebJobs - 添加没有属性的触发器?
- java - Java,括号放置问题{}