jQuery Anchor Offset仅在页面加载browserproblem上

时间:2014-09-23 12:14:27

标签: javascript jquery html anchor

我有这个javascript来偏移带有anchorlinks的页面中的固定标题(仅当页面加载了一个锚链接时):

(function() {
        if (document.location.hash) {
            setTimeout(function() {
                window.scrollTo(window.scrollX, window.scrollY - 100);
            }, 10);
        }
    })();

问题是这只适用于chrome。在firefox中,第一个锚链工作完全正常,但第二个,第三个等关闭(第二个200xp,第三个300px等)。它在IE11中根本不做任何事情。 有没有办法在纯jquery中执行此操作以获得更好的浏览器兼容性?或者为什么firefox和IE关闭以及chrome工作?

3 个答案:

答案 0 :(得分:0)

尝试侦听onscroll事件,然后运行。

$(window).scroll(function(){
    $(window).scrollTop($(window).scrollTop() - 100);
});

答案 1 :(得分:0)

下面是一个方便的jQuery函数,我用来漫步到任何元素,也是jsfiddle

$(".js-scrollto").click(function() {
    $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top
    }, 2000);
    return false;
});

答案 2 :(得分:0)

我在这里找到答案:offsetting an html anchor to adjust for fixed header

/**
* Check an href for an anchor. If exists, and in document, scroll to it.
* If href argument omitted, assumes context (this) is HTML Element,
* which will be the case when invoked by jQuery after an event
*/
function scroll_if_anchor(href) {
href = typeof(href) == "string" ? href : $(this).attr("href");

// If href missing, ignore
if(!href) return;

// You could easily calculate this dynamically if you prefer
var fromTop = 50;

// If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo)
// Legacy jQuery and IE7 may have issues: https://stackoverflow.com/q/1593174
if(href.charAt(0) == "#") {
    var $target = $(href);

    // Older browsers without pushState might flicker here, as they momentarily
    // jump to the wrong position (IE < 10)
    if($target.length) {
        $('html, body').animate({ scrollTop: $target.offset().top - fromTop });
        if(history && "pushState" in history) {
            history.pushState({}, document.title, window.location.pathname + href);
            return false;
        }
    }
}
}    

// When our page loads, check to see if it contains and anchor
scroll_if_anchor(window.location.hash);

// Intercept all anchor clicks
$("body").on("click", "a", scroll_if_anchor);

https://stackoverflow.com/users/1773904/ian-clark