我有一个使用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>
答案 0 :(得分:1)
我无法在链接上找到您的代码,但是看到您的网站,我会想到以下几点:
1)设置点击回调时,您的向下箭头不存在,稍后会添加该键入效果,因此不会在该A标签上设置点击回调。我想您使用的那个库中有一些事件可以让您知道效果已经完成,然后您可以为该A标签设置回调
2)自上而下的箭头上有href="#"
,该行未明确选择用于行.not('[href="#"]')
的click函数,我想您是从其他地方复制了该函数的,您可以添加一个该标签的href后面的id并在网站顶部添加一个带有该ID的元素
编辑:要修复向下箭头事件侦听器,我会这样做:
1,将函数移到参数之外
function scroll_to_hash(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
};
});
}
}
}
// Select all links with hashes
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(scroll_to_hash);
2,我猜您正在使用Typed.js,您有一个onComplete
回调https://mattboldt.com/typed.js/docs/,然后您可以在选项上为该回调设置向下箭头的click事件初始化插件
onComplete: function(self) {
$('a[href="#web-apps"]').click(scroll_to_hash)
}