2017-02-22 59 views
0

我有4个div,我想要应用滚动操作。JQuery Scroll DRY

该代码的作品,如果我重复它为每个部门,但我想只有一个代码块来处理事件。

,工程的代码是这样的 -

$('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) 
}); 

当上面的代码应用和链接被点击的页面只能下降几个像素。

谢谢你的帮助。

干杯,

瑞安

+1

什么是'.nav-text'和'这里nav',和为什么每次点击时'navText'永远不会是相同的jQuery集合?你应该发布一个HTML例子,以及它应该如何工作 – adeneo

回答

0

有几个问题:

  • 你的变量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) 
});