我希望我的锚链接在div之前停止

时间:2013-11-22 19:00:31

标签: javascript jquery html css

我有一个jquery脚本,为我的锚链接添加了“缓动”效果,唯一的问题是现在我有一个粘性导航,所以当导航滑动到DIV时,它隐藏了部分内容。

有没有办法在导航开始之前滑动导航?

锚点链接缓和效果:

$(function () {
    "use strict";
    var $root = $('html, body');
    $('a').click(function () {
        var href = $.attr(this, 'href');
        $root.animate({
            scrollTop: $(href).offset().top
        }, 500, function () {
            window.location.hash = href;
        });
        return false;
    });
});

HTML

        <nav>
            <ul class="navigation">
                    <li><a href="#donate">How to donate</a></li>
                    <li><a href="#locations">Drop-off locations</a></li>
                    <li><a href="#party">Party details</a></li>
            </ul>
        </nav>

感谢。

2 个答案:

答案 0 :(得分:1)

我将使用此代码从顶部到所需部分进行一次号召性用语(纯JavaScript)

const scrollerBtn = document.getElementById('btn');
const sectionView= document.getElementById('section-view');
var headerHeight = document.getElementById('main-header').offsetHeight;

scrollerBtn.addEventListener('click', () => {

    // scroll to your element
    sectionView.scrollIntoView(true);

    // now calculate fixed header
    var scrolledY = window.scrollY;

    if (scrolledY) {
        window.scroll(0, (scrolledY - headerHeight));
    }
})

答案 1 :(得分:0)

需要从滚动计算中减去标题的高度。 scrollTop: $(href).offset().top - header.height()

注意:此处,“标题”指的是您用作固定导航的任何html元素。

相关问题