我正在尝试编写 jQuery 代码,该代码将使页面滚动到 div,而不是立即转到那里,并使其尽可能简单。我已将所需 div 的 id 添加到 li 元素。
我的 html 代码如下所示:
<li id="#slide1" class="active" onclick="javascript:location.href='#slide1'"><a href="#slide1" title="Next Section" >About</a></li>
<li id="#slide2" onclick="javascript:location.href='#slide3'"><a href="#slide2" title="Next Section">Works</a></li>
<li id="#slide3" onclick="javascript:location.href='#slide3'"><a href="#slide3" title="Next Section">Contact</a></li>
<li id="#slide4" onclick="javascript:location.href='#slide4'"><a href="#slide4" title="Next Section">belekas</a></li>
<li id="#slide5" onclick="javascript:location.href='#slide5'"><a href="#slide3" title="Next Section">dar vienas</a></li>
我尝试了这个 jQuery 代码,但它不起作用。那么也许有人可以帮助我?
$('li').click(function(){
var target = $(this).attr('id');
$("html, body").animate({
scrollTop: target.offset().top
}, 1000);
return false;
});
更新: https://jsfiddle.net/j452hL2w/这是我的导航的 fiddle 版本
最佳答案
我从每个列表项中删除了每个 onclick="javascript:location.href='#slide'"
。这不是必需的,因为您是在 JavaScript 中创建点击处理程序的。
我用这个替换了你的点击函数:
$('li').click(function(e) {
// Prevent default action (e.g. jumping to top of page)
e.preventDefault();
// Create a variable with the link found in the list-item
var link = $(this).children('a');
// Animate the document
$('html,body').animate({
// Gets the href from the link ('slideX') and scrolls to it on the page.
scrollTop: $(link.attr('href')).offset().top
// 'slow'(600ms) can be replaced by 'fast'(200ms) or a number in ms.
// The default is 400ms
}, 'slow');
});
这是updated fiddle .
关于javascript - li元素的平滑滚动onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37515651/