滚动到div -多个位置



我有一个菜单列表,用户可以滚动到不同的部分。

问题是,我使用的代码是指特定的ID,所以我必须一遍又一遍地复制改变IDs:

$('#asistentes-menu').click(function() {
    $('body,html').animate({
        scrollTop: $("#asistentes-location").offset().top - 80
    }, 800);
});
$('#evento-menu').click(function() {
    $('body,html').animate({
        scrollTop: $("#event-section").offset().top - 80 
    }, 800);
});
and so on...

任何想法如何改变这段代码,所以我可以使用它的所有菜单位置?

您可以为菜单项使用类,然后可能为它指向的位置使用数据属性:

<a class="menu-item" data-location="asistentes-location">...</a>
...
<div id="asistentes-location">...</div>

和相应的脚本:

$('.menu-item').click(function() {
    var $menuItem = $(this);
    $('body,html').animate({
        scrollTop: $('#' + $menuItem.data('location')).offset().top - 80
    }, 800);
});

或者,您也可以使用一些字符串操作使用菜单项的ID来查找位置的ID:

$('#' + $menuItem.attr('id').replace('menu', 'location'))

UPDATE:如果你的菜单项是<a>标签,你可以简单地使用他们的href属性。我建议这样做,因为它不会破坏你的代码,即使javascript被禁用。

<a href="#myLocation" class="menu-item">...</a>

和相应的脚本:

$('.menu-item').click(function(e) {
    e.preventDefault();
    var $menuItem = $(this);
    $('body,html').animate({
       scrollTop: $($menuItem.attr('href')).offset().top - 80
    }, 800);
});

$(function() {
  $('.menu-item').click(function(e) {
    e.preventDefault();   // Remember to add this
    var $menuItem = $(this);
    $('body,html').animate({
      scrollTop: $($menuItem.attr('href')).offset().top - 80
    }, 800);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#location1" class="menu-item" data-location="location1">Go to 1</a>
<a href="#location2" class="menu-item" data-location="location2">Go to 2</a>
<a href="#location3" class="menu-item" data-location="location3">Go to 3</a>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p id="location1">This is location 1</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p id="location2">This is location 2</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<p id="location3">This is location 3</p>

最新更新