【问题标题】:Smooth Scrolling to anchor with the ability to interrupt animation with scroll?平滑滚动以通过滚动中断动画的能力锚定?
【发布时间】:2015-05-13 15:40:55
【问题描述】:

我有这个 Jquery 的 sn-p 用于平滑滚动到锚点:

<li><a href="#home">Home</a></li>

带你去……

<a name="home"></a>

.

var $root = $('html, body');
$('a').click(function() {
var href = $.attr(this, 'href');
$root.stop().animate({
    scrollTop: $(href).offset().top
}, 500, function () {
    window.location.hash = href;
});
return false;
});

效果很好,但是如果你再次滚动,有没有办法停止动画,现在这必须完成 500 毫秒,并且在动画时尝试滚动时会变得紧张......

任何帮助都会很棒,谢谢!

【问题讨论】:

  • JavaScript 位于文档的哪个位置?
  • 另外,将&lt;a name="home"&gt;&lt;/a&gt; 更改为&lt;a id="home"&gt;&lt;/a&gt;,因为# 指的是id,而不是name
  • @Patrick,谢谢,它是使用 google api 库链接的头部链接

标签: javascript jquery html


【解决方案1】:

这应该可行。从他对let user scrolling stop jquery animation of scrolltop?的回答中感谢@TomBates@

var $root = $('html, body');

$('a').click(function() {
  var href = $.attr(this, 'href');

  $root.stop().animate({
    scrollTop: $(href).offset().top
  }, 500, function() {
    window.location.hash = href;
  });

  return false;
});

$root.bind('scroll mousedown DOMMouseScroll mousewheel keyup touchstart', function(e) {
  if (e.which > 0 || e.type === 'mousedown' || e.type === 'mousewheel' || e.type === 'touchstart') {
    $root.stop();
  }
});
.home, .footer {
    width: 100%;
    height: 600px;
}

.home {
    background-color: #0FF;
}

.footer {
    background-color: #FF0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="home">
    <a id="home"></a>
</div>
<div class="footer">
    <a href="#home">Home</a>
</div>

【讨论】:

  • 在您提供的代码之后,在定义$root 的上下文中。
  • 所以像 var $root = $('html, body'); $('a').click(function() { var href = $.attr(this, 'href'); $root.stop().animate({ scrollTop: $(href).offset().top } , 10000, function () { window.location.hash = href; }); return false; }); $(window).scroll(function() { $root.stop(); }); ?对不起 jquery 新手 :)
  • @OllyF 请在您的问题中提供相关的 HTML,否则我无法判断它是否有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-24
  • 1970-01-01
  • 2015-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多