admin管理员组文章数量:1429841
I use this function to scroll to a desired container:
function scrolear(destino){
var stop = $(destino).offset().top;
var delay = 1000;
$('body').animate({scrollTop: stop+'px'}, delay);
return true;
}
The problem es when is used like this:
<a href="#" onclick="scrolear('#container');">go</a>
Because the href="#"
makes body to scroll to top of page.
Is there a way to prevent this?
I use this function to scroll to a desired container:
function scrolear(destino){
var stop = $(destino).offset().top;
var delay = 1000;
$('body').animate({scrollTop: stop+'px'}, delay);
return true;
}
The problem es when is used like this:
<a href="#" onclick="scrolear('#container');">go</a>
Because the href="#"
makes body to scroll to top of page.
Is there a way to prevent this?
Share Improve this question edited Nov 15, 2011 at 11:47 Anne 27.1k9 gold badges67 silver badges71 bronze badges asked Nov 15, 2011 at 11:46 Toni Michel CaubetToni Michel Caubet 20.2k58 gold badges218 silver badges388 bronze badges4 Answers
Reset to default 2Update
Consider using javascript to progressively enhance your site rather than relying on it for the site to function correctly. In your example this would be achievable by the following:
HTML:
<a href="#container">go</a>
Javascript:
$(function() {
$('a[href^="#"]').click(function(e) {
e.preventDefault();
var target = $(this).attr('href');
var stop = $(target).offset().top;
var delay = 1000;
$('body').animate({scrollTop: stop + 'px'}, delay);
});
});
This would intercept clicks on all links where the href started with a # and add in the animation for you. If the user did not have javascript enabled clicking the link would still take them to the correct place.
Hope this helps!
<a href="javascript:void(0);" onclick="scrolear('#container');">go</a>
This will just assign a javascript function to the href, which will do nothing at all,so no page scroll happens like with #
since you use jquery I would do
<a href="#">go</a>
$("a").click(function() {
e.preventDefault(); // cancel's the '#' click event
scrolear('#container');
});
corrected answer from @rich.okelly
function scrollTosec(){
$('a[href^="#"]').click(function(e) {
e.preventDefault();
var target = $(this).attr('href');
var stop = $(target).offset().top;
var delay = 200;
$('body').animate({scrollTop: stop + 'px'}, delay);
});
}
本文标签: javascriptjquery scrollTop and hrefquotquotStack Overflow
版权声明:本文标题:javascript - jquery scrollTop and href="#" - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745504311a2661175.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论