【问题标题】:JQuery Scroll DRYJQuery Scroll DRY
【发布时间】:2017-02-22 21:23:53
【问题描述】:

我有 4 个 div 想要应用滚动操作。

如果我为每个 div 重复该代码,但我只想有一个代码块来处理事件。

有效的代码是这样的 -

$('nav').on('click', function(){ 
$('html, body').animate({ scrollTop: $('#about').offset().top}, 1000)
});

我现在想使用的代码是这样的 -

var navText = $('.nav-text').on('click', function() {
            var txt = $(this).attr('id');
            var id = '#' + txt;
            console.log(id);
        });
$('nav').on('click', function(){ 
$('html, body').animate({ scrollTop: $(navText).offset().top}, 1000)
}); 

当应用上述代码并点击链接时,页面只会下降几个像素。

感谢您的帮助。

干杯,

瑞恩

【问题讨论】:

  • 这里的.nav-textnav 是什么,为什么每次点击时navText 都不是同一个jQuery 集合?您可能应该发布一个 HTML 示例以及它应该如何工作

标签: jquery scroll dry


【解决方案1】:

有几个问题:

  • 您的变量 navText 包含点击处理程序,而不是您要查找的 id
  • 根据您的代码结构,我假设您使用了重复的 ID,这可能会导致问题

在不知道您的标记的情况下,此代码可以为您工作:

HTML

<a href="#" data-id="id1" class="nav-text"></a>

JS

$('.nav-text').on('click', function(e) {
    e.preventDefault();
  var dataId = $(this).data('id');
  $('html, body').animate({
    scrollTop: $('#' + dataId).offset().top
  }, 1000)
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多