【发布时间】:2018-11-09 21:19:41
【问题描述】:
我有一个使用 jQuery 平滑滚动功能的 Rails 应用程序。平滑滚动适用于导航栏链接,但不适用于“向下滚动”箭头或“返回顶部”箭头。我尝试添加一个脚本标记来直接在元素上实现该行为,但没有运气。任何建议表示赞赏!
这里是滚动功能-
// Select all links with hashes
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
这是包含向下箭头的块。带有(这里有一些文字)的括号不在我的实际代码中,我只是将其更改为 S/O。 -
<div class="typebox" style="min-height: 119px;">
<div id="typed-strings">
<h3 class="type-active"><strong style="font-size: 20px; line-height: 1.5em;"> (some text here) <br> (some more text here) <br><br><a href="#web-apps"><%= image_tag "down-arrow.png", class: "down-arrow"%></a></strong></h3>
</div>
<span id="typed"></span>
<br />
</div>
【问题讨论】:
-
点击是否触发回调?您是否检查过是否在该功能上找到了
target?在if (target.length)行上放一个断点,您可以检查target变量。你能创建一个 codepen/jsfiddle 来重现这个问题吗? -
我对断点还不是很熟悉,但这是我网站的链接。 www.justincefai.co
标签: jquery html ruby-on-rails scroll