javascript - 当用户滚动到部分时更新位置哈希

标签 javascript html css

我想在用户到达页面上的某个点时更新 window.location.hash 值。

例如如果用户滚动到 ID = 'about' 的 div,我希望更新 url。

就像您单击自动将您滚动到页面上的 anchor 的链接一样,它会更新 URL 中的哈希值。

我设想通过检测元素是否可见来实现此目的,如果可见,则更新 window.location.hash = elementsID

接受其他建议。

我正在使用 React 并试图避免使用 JQuery,因此非常感谢 vanilla JS 建议。谢谢。

编辑:

感谢您的建议。设法用 vanilla JS 组合一个解决方案,并在 React 组件中实现它。代码仍然需要清理,但你明白了要点

class HomeView extends React.Component{

    constructor () {
    super();

    this.state = {
      hash: '#'
    }

    this.elements = {}
  }

  componentDidMount(){
    this.scrollListener();
  }

  componentDidUpdate(prevProps){
    if(this.props.location.hash !== prevProps.location.hash){
        this.scrollToHash(this.props.location.hash)
    }

  }

  scrollListener(){
    window.addEventListener('scroll', (event) => {

        if(window.pageYOffset > 0 && window.pageYOffset < this.elements.about.offsetTop  - 200){
            const hash = '#';
            this.setState({hash: hash}, () => {
                history.pushState('', '', hash);
                this.updateHashState(hash);

            })

        } else if(window.pageYOffset > this.elements.about.offsetTop - 200 && window.pageYOffset < this.elements.skills.offsetTop - 200) {
            const hash = '#about';
            this.setState({hash: hash}, () => {
                history.pushState('', '', hash);
                this.updateHashState(hash);

            })

        } else if(window.pageYOffset > this.elements.skills.offsetTop - 200 && window.pageYOffset < this.elements.contact.offsetTop - 200) {
            const hash = '#skills';
            this.setState({hash: hash}, () => {
                history.pushState('', '', hash);
                this.updateHashState(hash);

            })

        }else if(window.pageYOffset > this.elements.skills.offsetTop - 200) {
            const hash = '#contact';
            this.setState({hash: hash}, () => {
                history.pushState('', '', hash);
                this.updateHashState(hash);

            })

        }

    })
  }

  updateHashState(hash) {
    switch(hash){
        case '#about':
            this.setState({
                forward: '#skills',
                back: '#'
            })
            break;
        case '#skills':
            this.setState({
                forward: '#contact',
                back: '#about'
            })
            break;
        case '#contact':
            this.setState({
                forward: '',
                back: '#skills'
            })
            break;
        default:
            this.setState({
                forward: '#about',
                back: ''
            })
            break;
    }
  }




    render(){

        return(
            ...
        )

    }

}

export default HomeView

最佳答案

看看我的提议。 jQuery 代码将捕获所有 <section>文档加载后的选择器并从 data-hash 设置适当的哈希值滚动时的属性。

$(document).ready(function(){
  var sections = {};
  
  $(".section").each(function(){
  	var hash = $(this).data("hash"),
            topOffset = $(this).offset().top;
        sections[topOffset] = hash;
  });
  
  $(window).scroll(function(e){
  	var scrollTop = $(window).scrollTop();
        setHash(scrollTop);
  });
  
  function setHash(st){
  	var hash = "";
  	for(section in sections){
    	if (section < st + ($(window).height()/2)) hash = sections[section];
    }
    console.log(`SETTING HASH: ${hash}`);
    window.location.hash = hash;
  }
});
section{
  position: relative;
  display: block;
  width: 100%;
  height: 800px;
  background: #fff;
  border-bottom: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="section" data-hash="about">
  #about
</section>
<section class="section" data-hash="works">
  #works
</section>
<section class="section" data-hash="contact">
  #contact
</section>

关于javascript - 当用户滚动到部分时更新位置哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43303083/

相关文章:

javascript - 在 Angular js中将id传递给json数据

javascript - 提交表单并重新加载

javascript 将 cookie 设置为 httponly

html - 为什么一个div高度的变化是px而不是百分比?

html - Bootstrap中元素的位置

css - div 的背景相对于 chrome 中的页面不居中

javascript - 使用 moment.js 将天数添加到区域设置特定日期

html - 调整屏幕大小时问题居中 Logo

css - 仅使用 HTML 和 CSS 的 flex 帆形?

css - 如何将无序列表中的内容完美居中?