繁体   English   中英

如何防止阅读更多/阅读更少按钮跳到底部?

[英]How to prevent Read More/Read less button to jumping to the bottom?

我已经为阅读更多/阅读更少功能创建了一个按钮,但是当我点击 show less 时,它会跳到底部。 你能告诉我如何解决这个问题吗?...它应该是 go 到相同的 position...我正在使用氧气生成器(此代码 [https://codepen.io/nick7961/pen/qByYMXZ?editors= 0010])

这样做的一种方法是获取当前滚动 y 值并将其除以主体高度以获得滚动 position 的百分比。 在进行更改之前,您必须在事件侦听器中执行此操作。 在我的function,setScroll,可以得到新的body height,乘以之前抓取的百分比,保持scroll在同一个relative position。

button.addEventListener('click', () => {
   const defaultValue = {
      element: arrowIcon,
      currentIcon: 'fa-chevron-down',
      newIcon: 'fa-chevron-up',
   };
  
  //show content  
  if (initial.showAllContent){

     showButton(buttonShowLess);
     showButton(buttonShowMore, false);

     content.classList.remove('gradientContent', 'maxContentHeight');
  }else{
    let relativeScroll = window.scrollY / document.body.clientHeight;

    showButton(buttonShowLess, false);
    showButton(buttonShowMore);

    defaultValue.currentIcon = 'fa-chevron-up';
    defaultValue.newIcon = 'fa-chevron-down';
    
    content.classList.add('gradientContent', 'maxContentHeight');
   
    setScroll(relativeScroll);
  }

  changeIcon(defaultValue);
  initial.showAllContent = !initial.showAllContent;  

});

function setScroll(relativeScroll) {
    let scrollValue = document.body.clientHeight * relativeScroll;
    window.scroll(0, scrollValue);
}

如果你想将用户弹回顶部,你可以简单地使用:

window.scroll(0, 0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM