首页 > 解决方案 > 如何根据位置更改粘性向上箭头按钮的属性?

问题描述

我的网页有一个粘性向上箭头图像,如下所示:

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;
}

现在,我想根据它在屏幕上的变化位置来改变按钮的颜色。当我滚动页面时,粘性按钮将位于不同的部分,如下所示。网页布局1 如果粘性按钮在 A 部分,它应该是红色的。如果它在 B 部分,它应该是蓝色的。网页布局2请注意,移动的是页面,而不是按钮。按钮处于固定位置。

为此,我需要粘性按钮在任何给定时刻重叠的部分的 ID。有没有办法通过 JavaScript 获取这些信息?

PS:我已经调整了细节以使事情更加清晰。这是正在移动的页面。那么,如果我使用Element.getBoundingClientRect()for #myBtn,无论我在页面上滚动到哪里,我都不会得到相同的 top/y 值吗?

标签: javascripthtmlcssstickysticky-footer

解决方案


在这里,我做了一个示例供您测试和实现。

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>


推荐阅读