动态内容的 scrollTo 功能
scrollTo functionality for dynamic content
我正在尝试为页面较高的内容创建一个 'scrollTo' link 到页面较低的具有更多信息的位置。我目前使用下面的代码为一个项目工作。两组代码都可以根据需要修改。
标记(树枝):
<a id="scroll-src-{{ term.id }}" class="content-scroll">
<!-- other page content -->
<div id="scroll-dest-{{ term.id }}" class="content-scroll"></div>
jQuery:
if($('.content-scroll').length) {
$('#scroll-src-16').click(function() {
$('html, body').animate({
scrollTop: $('#scroll-dest-16').offset().top - 87
}, 750);
});
}
如您所见,我只对一项工作:术语 16
。我怎样才能 abstract/modify 这与所有 term ids 一起工作?
这是在 Drupal 8 中构建的,并利用了视图模块。我不确定是否需要使用 drupal.settings / drupal.behaviors 来获得最佳解决方案。
尝试...
Jquery
if($('.content-scroll').length) {
$('.scroll-link').click(function() {
var number = $(this).attr('data-scroll-id');
$('html, body').animate({
scrollTop: $('#scroll-dest-'+number).offset().top - 87
}, 750);
});
}
HTML
<a id="scroll-src-{{ term.id }}" data-scroll-id="{{ term.id }}" class="scroll-link content-scroll">
<!-- other page content -->
<div id="scroll-dest-{{ term.id }}" class="content-scroll"></div>
<a id="scroll-src-{{ term.id }}" class="content-scroll button" data-id="{{ term.id }}">
<!-- other page content -->
<div id="scroll-dest-{{ term.id }}" class="content-scroll"></div>
if($('.content-scroll').length) {
$('.button').click(function() {
$('html, body').animate({
scrollTop: $('#scroll-dest-'+$(this).data('id')).offset().top - 87
}, 750);
});
}
我建议给每个按钮一个数据属性和一个 class 来绑定点击。在点击事件中使用数据属性滚动到正确的ID。
我正在尝试为页面较高的内容创建一个 'scrollTo' link 到页面较低的具有更多信息的位置。我目前使用下面的代码为一个项目工作。两组代码都可以根据需要修改。
标记(树枝):
<a id="scroll-src-{{ term.id }}" class="content-scroll">
<!-- other page content -->
<div id="scroll-dest-{{ term.id }}" class="content-scroll"></div>
jQuery:
if($('.content-scroll').length) {
$('#scroll-src-16').click(function() {
$('html, body').animate({
scrollTop: $('#scroll-dest-16').offset().top - 87
}, 750);
});
}
如您所见,我只对一项工作:术语 16
。我怎样才能 abstract/modify 这与所有 term ids 一起工作?
这是在 Drupal 8 中构建的,并利用了视图模块。我不确定是否需要使用 drupal.settings / drupal.behaviors 来获得最佳解决方案。
尝试...
Jquery
if($('.content-scroll').length) {
$('.scroll-link').click(function() {
var number = $(this).attr('data-scroll-id');
$('html, body').animate({
scrollTop: $('#scroll-dest-'+number).offset().top - 87
}, 750);
});
}
HTML
<a id="scroll-src-{{ term.id }}" data-scroll-id="{{ term.id }}" class="scroll-link content-scroll">
<!-- other page content -->
<div id="scroll-dest-{{ term.id }}" class="content-scroll"></div>
<a id="scroll-src-{{ term.id }}" class="content-scroll button" data-id="{{ term.id }}">
<!-- other page content -->
<div id="scroll-dest-{{ term.id }}" class="content-scroll"></div>
if($('.content-scroll').length) {
$('.button').click(function() {
$('html, body').animate({
scrollTop: $('#scroll-dest-'+$(this).data('id')).offset().top - 87
}, 750);
});
}
我建议给每个按钮一个数据属性和一个 class 来绑定点击。在点击事件中使用数据属性滚动到正确的ID。