2013-07-06 62 views
0

我试图通过改变一堆重复的函数来遵循DRY原则,但我被困在这里。我想这个滚动更改为与不同IDS一个更通用的方法重复4次函数(我使用jQuery的):jquery scrollTop函数的问题

$('.empresa').click(function(event){ 
    $('html, body').animate({ 
     scrollTop: $("#empresa").offset().top 
    }, 500); 
    return false; 
    }); 
    $('.nosotros').click(function(event){ 
    $('html, body').animate({ 
     scrollTop: $("#nosotros").offset().top 
    }, 500); 
    return false; 
    }); 

的类的元素在ul中导航看起来像这样。

<ul class="nav"> 
    <li><a href="index#nosotros" class="nosotros">Link to the anchor</a></li> 
    <li><a href="index#empresa" class="empresa">Link to the anchor</a></li> 
</ul> 

并且滚动到标签是具有该标签的div元素。

<div class="some-random-class" id="empresa" name="empresa"> 
<div class="some-random-class" id="nosotros" name="nosotros"> 

我就是用这个新的选择,以抢班名单与适当的锚,但我在使用的功能的滚动部分的麻烦,我不知道用/转换类或提取到一个ID的对象的名称,所以我可以继续使用它,就像我以前做的一样。

$('.nav li').children('a').click(function() { 
    alert($(this).attr('class')); 
}); 

希望你们能帮助我!

回答

2
$('.nav > li > a').click(function(e){ 
    e.preventDefault(); 
    $('html,body').animate({ 
     scrollTop: $('#'+$(this).prop('class')).offset().top 
    }); 
}); 
0

您还可以使用:

$('.fluidJump').on('click', function(event) { 
    event.preventDefault(); 
    var offset = $($(this).attr('href')).offset().top; 
    $('html, body').animate({scrollTop:offset}, 500); 
}); 

添加 “fluidJump” 上hiperlink类我一起去参加动画节。 (数值)

<a href="#sectionid">Go to section</a>