我有一个菜单列表,用户可以滚动到不同的部分。
问题在于,我使用的代码指的是特定的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...
知道如何更改此代码以便我可以将其用于所有菜单位置吗?
答案 0 :(得分:2)
您可以将类用于菜单项,然后可以使用数据属性指向它指向的位置:
<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'))
更新:如果您的菜单项为<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);
});
});
&#13;
<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>
&#13;