javascript 在JS中向下滚动300px一页后,如何显示链接?

y1aodyip  于 2022-10-30  发布在  Java
关注(0)|答案(3)|浏览(139)

我试图在我的网站上向下滚动300px后,使一个锚定到标题的链接出现,但我的代码似乎不起作用。有人知道为什么吗?注意我在我的网站上使用Bootstrap5。
"这是我的密码"

<a href="#header-title-1" id="customID" class="bottom-0 end-0 quick-anchor-top hide"> <i
      class="fa-solid fa-arrow-up"></i></a>

.quick-anchor-top {
    font-size: 25px;
    padding: 15px 25px 15px 25px;
    border-radius: 50px;
    color: rgb(0, 0, 0);
    background-color: rgba(182, 20, 20, 0.800);
    transition: all 0.4s ease;
    margin: 20px;
    position: fixed;
    z-index: 1;
}

.quick-anchor-top:hover {
    transition-duration: 0.4s;
    color: white;
    background-color: rgba(0, 0, 0, 0.800);
}

myID = document.getElementById("customID");

var myScrollFunc = function() {
  var y = window.scrollY;
  if (y >= 300) {
    myID.className = "quick-anchor-top show"
  } else {
    myID.className = "quick-anchor-top hide"
  }
};

window.addEventListener("scroll", myScrollFunc);
bweufnob

bweufnob1#

JavaScript代码正常工作:出现showhide CSS类名称。问题出在CSS中。因此,要解决此问题,请尝试以下操作:

.quick-anchor-top {
  font-size: 25px;
  padding: 15px 25px 15px 25px;
  border-radius: 50px;
  color: rgb(0, 0, 0);
  background-color: rgba(182, 20, 20, 0.800);
  transition: all 0.4s ease;
  margin: 20px;
  position: fixed;
  z-index: 1;
  display: none;
}

.quick-anchor-top.show {
  display: block;
}

.quick-anchor-top.hide {
  display: none; 
}

.quick-anchor-top:hover {
  transition-duration: 0.4s;
  color: white;
  background-color: rgba(0, 0, 0, 0.800);
}
r1wp621o

r1wp621o2#

当页面刚加载时,您不需要设置

class="bottom-0 end-0 quick-anchor-top hide"

将标记更改为

<a href="#header-title-1" id="customID" > <i
        class="fa-solid fa-arrow-up"></i></a>

将if else更改为

if (y >= 300) {
        myID.className = "quick-anchor-top"
    } else {
        myID.className = ""
    }
wsewodh2

wsewodh23#

这不是添加或删除类的正确方法。另外,我建议根据您需要处理事件的方式使用去抖动或节流,因为滚动事件可以在一秒钟内运行几百次。

const myID = document.getElementById("customID");

// Reset timeout after each call
const debounce = function (func, duration = 250){
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, duration);
  };
}

// Call only once per duration
function throttle(func, duration = 250) {
  let shouldWait = false
  return function (...args) {
    if (!shouldWait) {
      func.apply(this, args)
      shouldWait = true
      setTimeout(function () {
        shouldWait = false
      }, duration)
    }
  }
}

// Handle scroll Event
const scrollHandler = function() {
  const { scrollY } = window;
  if ( scrollY >= 300) {
    myID.classList.add('show');
    myID.classList.remove('hide');
  } else {
    myID.classList.add('hide');
    myID.classList.remove('show');
  }
};

window.addEventListener("scroll", throttle(() => scrollHandler()) );

相关问题