简体   繁体   English

jQuery跳到锚点上方100px

[英]jQuery jump to 100px above anchor

Instead of the window jump so that the anchor is at the top of the page, I'd like it to be 100px below the top of the page. 我希望窗口位于页面顶部下方100px,而不是窗口跳转使锚位于页面顶部。 I don't want to animate, and I'd rather it didn't jump twice. 我不想设置动画,我希望它不会跳两次。

I'd like it to be a general solution. 我希望它是一个通用的解决方案。

This is what I have tried but it doesn't seem to work... 这是我尝试过的方法,但似乎不起作用...

$("a.inpage").click(function (e) {
    e.preventDefault();
    $(":target").each(function () {
        var targetpos = $(this).position();
        var scrollpos = targetpos.top - 100;
        window.scrollTo(0,scrollpos);
    })
}

Thanks, David 谢谢大卫

:target CSS3 selector matches element which id is the part of the URL. :target CSS3选择器匹配ID为URL一部分的元素。 But you are using ev.preventDefault() so you do not follow the link and URL does not change 但是您使用的是ev.preventDefault(),因此您不遵循链接并且URL不会更改

It is better to do smth like 最好像

$("a.inpage").click(function (e) {
    e.preventDefault();
    var targetpos = $($(this).attr('href')).position(); // note this line
    var scrollpos = targetpos.top - 100;
    window.scrollTo(0,scrollpos);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM