如何捕获由哈希bang锚链接引起的滚动事件?

3

我在想是否有更好的方法来解决这个问题。

假设你有一个使用锚点标签的“跳转到”链接:

www.example.com/#about

打开该链接将使浏览器本地自动滚动到具有

<div id="about"></div>

现在,我想捕获此scroll事件,以便我可以添加更多的offset以控制浏览器应使用多少滚动。

原因是我有一个fixed导航菜单,占用了浏览器的120px

问候,

3个回答

5
据我所知,没有直接拦截此行为的方法,即没有与用户可访问的事件相关联。相反,可以使用window.location.hash。一旦页面加载完成,您可以找到相关的元素并跳转到它。
例如,类似以下内容:
function jumpToElement(element, offset) {
  if (!offset) offset = 0;
  var verticalPos = element.offsetHeight;
  window.scrollTo(0, verticalPos + offset);
}
function jumpToHash(offset) {
  var hash = window.location.hash;
  // Do nothing if no hash exists
  if (typeof hash !== 'string' || !hash.length) return;
  var targetElement = document.querySelector(hash);
  // Do nothing if targetElement doesn't exist
  if (!targetElement) return;
  jumpToHash(targetElement, offset);
});
if (document.readyState === "complete") {
  jumpToHash(-120); // with 120px
} else {
  document.addEventListener("DOMContentLoaded", jumpToHash);
}

标记为答案是因为它是正确的,没有直接拦截这种行为的方法 - arvil
1
应该是:var targetElement = document.querySelector(hash); - iamrobert
@iamrobert 更新了答案以反映这一点。 - danielgormly

1
你可以使用jQuery的scroll()方法。当用户在指定元素中滚动时,滚动事件会发生,并且它适用于所有可滚动的元素和窗口对象(浏览器窗口)。scroll()方法触发滚动事件,或者附加一个函数来运行滚动事件。

为选定元素触发滚动事件:

$(selector).scroll()

将一个函数附加到滚动事件:

$(selector).scroll(function)

例子:

var $titlebar = $( '.titlebar' ),
    fixedPosition = function() {
      var pos1 = $titlebar.offset().top,
          winTop = $( window ).scrollTop();
          $( window ).scrollTop( winTop + 1 );
          var pos2 = $titlebar.offset().top;
          $( window ).scrollTop( winTop );
          return ( pos1 != pos2 )
    }(),
    titlebarHeight = fixedPosition ? $titlebar.outerHeight() : 0,
    $menu = $( '.nav a' );
        
$( '.nav a' ).click( function( e ) {
  var $target = $( this.hash );

  e.preventDefault();

  if ( !$( this ).hasClass( 'active' ) ) {
            $( 'html, body' ).stop( true, false ).animate( {
                'scrollTop': $target.offset().top - titlebarHeight
            }, 800 );
        }
    } );

$( window ).on( 'scroll', function() {
  didScroll = true
} );

setInterval( function() {
  if ( didScroll ) {
    didScroll = false;

    var scrollPos = $( document ).scrollTop(),
        windowHeight = ( $( window ).height() - titlebarHeight ) / 2;

        if ( fixedPosition ) {
          $menu.each( function( index ) {
            var $page = $( this.hash );

            if ( $page.position().top <= scrollPos + titlebarHeight + windowHeight ) {
              $( '.nav a.active' ).removeClass( 'active' );
              $menu.eq( index ).addClass( 'active' )
            }
          });
        }
  }
}, 150 );
html,
body,
.contents,
.contents div {
  padding: 0;
  margin: 0;
  height: 100%
}
.titlebar {
  width: 100%;
  position: fixed;
  background-color: black
}
ul {
  padding: 0;
  margin: 0;
  list-style: none
}
.nav li {
  display: inline
}
.nav a {
  display: inline-block;
  padding: 1em;
  color: white;
  text-decoration: none;
  -webkit-transition-duration: .2s;
     -moz-transition-duration: .2s;
       -o-transition-duration: .2s;
          transition-duration: .2s
}
.nav a:hover {
  background-color: #555;
}
.nav a.active,
.nav a.active:hover{
    color: #69452d;
    background-color: #e1ba89;
    cursor: default
}
#home {
  padding: 4em 1em 1em;
  background-color: #b6946b
}
#features {
  padding: 1em;
  background-color: #e1ba89
}
#buy {
  padding: 1em;
  background-color: #ddd
}
#contact {
  padding: 1em;
  background-color: white
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="titlebar">
  <ul class="nav">
    <li><a href="#home" class="active">Home</a></li
    ><li><a href="#features">Features</a></li
    ><li><a href="#buy">Buy</a></li
    ><li><a href="#contact">Contact</a></li>
  </ul>
</div>
<div class="contents">
  <div id="home">Home</div>
  <div id="features">Features</div>
  <div id="buy">Buy</div>
  <div id="contact">Contact Us</div>
</div>


0

你不需要使用JS,只需在CSS中将scroll-margin-top: 120px添加到该元素即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接