如何在加载页面时禁用锚点“跳转”?

时间:2022-02-13 01:22:35

I think this may not be possible, will try and explain as best as I can. I have a page containing tabs (jquery powered), controlled by the following:

我想这可能是不可能的,我会尽力解释。我有一个包含选项卡(jquery驱动)的页面,由以下内容控制:

I'm using this code, as provided by another user from a previous question.

我正在使用这段代码,就像其他用户从先前的问题中所提供的那样。

<script type="text/javascript">
    $(function() {

     $('html, body').animate({scrollTop:0}); // this is my "fix"

        var tabContent = $(".tab_content");
        var tabs = $("#menu li");
        var hash = window.location.hash;
     tabContent.not(hash).hide();
        if(hash=="") {
      $('#tab1').fadeIn();
     }
        tabs.find('[href=' + hash + ']').parent().addClass('active');

        tabs.click(function() {
            $(this).addClass('active').siblings().removeClass('active');
            tabContent.hide();
            var activeTab = $(this).find("a").attr("href");

            $(activeTab).fadeIn();
           return false;
        });

    });
</script>

this code works great when I visit the "tabs" page directly.

当我直接访问“选项卡”页面时,这段代码非常有效。

however, I need to link to invidual tabs from other pages - so to do this, the code gets the window.location.hash then shows the appropiate tab.

但是,我需要从其他页面链接到独立的选项卡—为此,代码获得windows .location。然后显示appropiate选项卡。

the page doesn't "jump" to the anchor because of "return false".

由于返回false,页面不会“跳转”到锚点。

this event is only triggered on a click event however. hence, if i visit my "tabs" from any other page, the "jump" effect is triggered. To combat this I automatically scroll to teh top of the page, but I would rather this didn't happen.

然而,此事件仅在单击事件上触发。因此,如果我从任何其他页面访问我的“选项卡”,就会触发“跳转”效果。为了解决这个问题,我自动滚动到页面的顶部,但我宁愿不要发生这种情况。

is there any way to simulate "return false" when the page loads, preventing the anchor "jump" from occuring.

是否有方法在页面加载时模拟“return false”,防止锚点“跳转”发生。

hope this is clear enough.

希望这一切足够清晰。

thanks

谢谢

14 个解决方案

#1


124  

Does your fix not work? I'm not sure if I understand the question correctly - do you have a demo page? You could try:

你的修复没有效果吗?我不确定我是否正确地理解了这个问题——你有演示页面吗?你可以试试:

if (location.hash) {
  setTimeout(function() {

    window.scrollTo(0, 0);
  }, 1);
}

Edit: tested and works in Firefox, IE & Chrome on Windows.
Edit 2: move setTimeout() inside if block, props @vsync.

编辑:在Firefox、IE和Chrome中测试和工作。编辑2:移动setTimeout(),如果block,道具@vsync。

#2


25  

See my answer here: * Answer

看我的回答:*回答

The trick is to just remove the hashtag ASAP and store its value for your own use:

窍门是尽快移除hashtag,并将其值存储到您自己的使用中:

It is important that you do not put that part of the code in the $() or $(window).load() functions as it would be to late and the browser already have moved to the tag.

重要的是,不要将代码的这一部分放在$()或$(窗口).load()函数中,因为它会延迟,浏览器已经移动到标记中。

// store the hash (DON'T put this code inside the $() function, it has to be executed 
// right away before the browser can start scrolling!
var target = window.location.hash,
    target = target.replace('#', '');

// delete hash so the page won't scroll to it
window.location.hash = "";

// now whenever you are ready do whatever you want
// (in this case I use jQuery to scroll to the tag after the page has loaded)
$(window).on('load', function() {
    if (target) {
        $('html, body').animate({
            scrollTop: $("#" + target).offset().top
        }, 700, 'swing', function () {});
    }
});

#3


11  

There are other ways of tracking what tab you're on; perhaps setting a cookie, or a value in a hidden field, etc etc.

还有其他方法可以跟踪你的标签;可能设置一个cookie,或者在隐藏字段中设置一个值,等等。

I would say that if you don't want the page jumping on load, you would be better off using one of these other options rather than the hash, because the main reason for using the hash in preference to them is to allow exactly what you're wanting to block.

我想说的是,如果你不想让页面加载,你最好使用其他选项而不是哈希,因为优先使用哈希的主要原因是允许你想要阻塞的东西。

Another point - the page won't jump if your hash links don't match the names of the tags in the document, so perhaps if you want to keep using the hash you could manipulate the content so that the tags are named differently. If you use a consistent prefix, you will still be able to use Javascript to jump between then.

另一点——如果您的散列链接与文档中标记的名称不匹配,页面不会跳转,因此,如果您希望继续使用散列,您可以对内容进行操作,以便以不同的方式命名标记。如果您使用一致的前缀,那么您仍然可以使用Javascript来跳转。

Hope that helps.

希望有帮助。

#4


10  

I used dave1010's solution, but it was a bit jumpy when I put it inside the $().ready function. So I did this: (not inside the $().ready)

我使用了dave1010的解决方案,但是当我把它放入$()时,它有点紧张。准备功能。所以我这样做了:(不在$().ready中)

    if (location.hash) {               // do the test straight away
        window.scrollTo(0, 0);         // execute it straight away
        setTimeout(function() {
            window.scrollTo(0, 0);     // run it a bit later also for browser compatibility
        }, 1);
    }

#5


8  

  1. Browser jumps to <element id="abc" /> if there are http://site.com/#abc hash in the address and the element with id="abc" is visible. So, you just should hide the element by default: <element id="anchor" style="display: none" />. If there is no visible element with id=hash at the page, the browser would not jump.

    如果地址中有http://site.com/#abc散列,并且id="abc"的元素是可见的,浏览器将跳转到 。因此,您应该默认隐藏元素: 。如果页面上没有id=hash的可见元素,浏览器将不会跳转。

  2. Create a script that checks the hash in url, and then finds and shows the prrpopriate element (that is hidden by default).

    创建一个脚本检查url中的散列,然后查找并显示prrpopriate元素(默认情况下是隐藏的)。

  3. Disable default "hash-like link" behaviour by binding an onclick event to a link and specify return false; as a result of onclick event.

    通过将onclick事件绑定到链接并指定返回false,禁用默认的“hashlink”行为。作为onclick事件的结果。

When I implemented tabs, I wrote something like that:

当我实现标签时,我写了这样的东西:

    <script>
    $(function () {         
        if (location.hash != "") {
            selectPersonalTab(location.hash);
        }
        else {
            selectPersonalTab("#cards");
        }
    });

    function selectPersonalTab(hash) {
        $("#personal li").removeClass("active");
        $("a[href$=" + hash + "]").closest("li").addClass("active");
        $("#personaldata > div").hide();
        location.hash = hash;
        $(hash).show();
    }

    $("#personal li a").click(function (e) {
        var t = e.target;
        if (t.href.indexOf("#") != -1) {
            var hash = t.href.substr(t.href.indexOf("#"));
            selectPersonalTab(hash);
            return false;
        }
    });
</script>

#6


2  

While the accepted answer does work well, I did find that sometimes, especially on pages containing large images that the scroll bar will jump about wildly using

虽然公认的答案确实有效,但我确实发现,有时候,特别是在包含大图片的页面上,滚动条会疯狂地使用这些图片

 window.scrollTo(0, 0);

Which can be quite distracting for the user.

这会让用户分心。

The solution I settled on in the end is actually pretty simple, and that's to use a different ID on the target to the one used in location.hash

我最后确定的解决方案实际上非常简单,那就是在目标上使用与location.hash中使用的ID不同的ID

Eg:

例如:

Here is the link on some other page

这是另一个页面的链接

<a href="/page/with/tabs#tab2">Some info found in tab2 on tabs page</a>

So of course if there is an element with an ID of tab2 on the tabs page the window will jump to it on load.

当然,如果标签页上有一个ID为tab2的元素,窗口会在加载时跳转到它。

So you can append something to the ID to prevent it:

所以你可以在ID上添加一些东西来防止它:

<div id="tab2-noScroll">tab2 content</div>

And then you can append "-noScroll" to location.hash in the javascript:

然后你可以附加“-noScroll”到位置。javascript的散列:

<script type="text/javascript">
    $(function() {

        var tabContent = $(".tab_content");
        var tabs = $("#menu li");
        var hash = window.location.hash;


     tabContent.not(hash + '-noScroll').hide();                           
        if(hash=="") {       //^ here
      $('#tab1-noScroll').fadeIn();
     }
        tabs.find('[href=' + hash + ']').parent().addClass('active');

        tabs.click(function() {
            $(this).addClass('active').siblings().removeClass('active');
            tabContent.hide();
            var activeTab = $(this).find("a").attr("href") + '-noScroll'; 
                                                               //^ and here

            $(activeTab).fadeIn();
           return false;
        });

    });
</script>

#7


2  

dirty CSS only fix to stay scrolled up every time the anchor is used (not useful if you still want to use anchors for scroll-jumps, very useful for deeplinking):

脏CSS只会在每次使用锚点时保持滚动(如果您仍然想要使用锚点进行滚动跳转,这对深度链接非常有用):

.elementsWithAnchorIds::before {
   content: "";
   display: block;
   height: 9999px;
   margin-top: -9999px; //higher thin page height
}

#8


1  

I think I've found a way for UI Tabs without redoing the functionality. So far I haven't found any problems.

我想我找到了一种不用重做功能的UI选项卡的方法。到目前为止我还没有发现任何问题。

    $( ".tabs" ).tabs();
    $( ".tabs" ).not(".noHash").bind("tabsshow", function(event, ui) { 
        window.location.hash = "tab_"+ui.tab.hash.replace(/#/,"");
        return false;
    });

    var selectedTabHash = window.location.hash.replace(/tab_/,"");
    var index = $( ".tabs li a" ).index($(".tabs li a[href='"+selectedTabHash+"']"));
    $( ".tabs" ).not(".noHash").tabs('select', index);

All within a ready event. It prepends "tab_" for the hash but work both when clicked and page loaded with hash.

一切都在准备就绪的情况下。它为散列预先写“tab_”,但在单击时和页面加载散列时都可以工作。

#9


1  

None of answers do not work good enough for me, I see page jumping to anchor and then to top for some solutions, some answers do not work at all, may be things changed for years. Hope my function will help to someone.

没有一个答案对我来说不够好,我看到page跳转到锚点,然后到顶部的一些解决方案,有些答案根本不起作用,可能事情会改变很多年。希望我的功能对某人有所帮助。

/**
 * Prevent automatic scrolling of page to anchor by browser after loading of page.
 * Do not call this function in $(...) or $(window).on('load', ...),
 * it should be called earlier, as soon as possible.
 */
function preventAnchorScroll() {
    var scrollToTop = function () {
        $(window).scrollTop(0);
    };
    if (window.location.hash) {
        // handler is executed at most once
        $(window).one('scroll', scrollToTop);
    }

    // make sure to release scroll 1 second after document readiness
    // to avoid negative UX
    $(function () {
        setTimeout(
            function () {
                $(window).off('scroll', scrollToTop);
            },
            1000
        );
    });
}

#10


0  

Another approach

Try checking if the page has been scrolled and only then reset position:

检查页面是否已滚动,然后重新设置位置:

var scrolled = false;

$(window).scroll(function(){
  scrolled = true;
});

if ( window.location.hash && scrolled ) {
  $(window).scrollTop( 0 );
}

Heres a demo

这是一个演示

#11


0  

I did not have much success with the above setTimeout methods in Firefox.

在Firefox中,在上面的setTimeout方法中,我没有取得多少成功。

Instead of a setTimeout, I've used an onload function:

我使用了onload函数,而不是setTimeout:

window.onload = function () {
    if (location.hash) {
        window.scrollTo(0, 0);
    }
};

It's still very glitchy, unfortunately.

不幸的是,它仍然很有光泽。

#12


0  

I have not had any consistent success with these solutions.

我在这些解决方案上没有取得任何一致的成功。

Apparently due to the fact that the jump happens before Javascript => reference(http://forum.jquery.com/topic/preventing-anchor-jump)

显然,这是因为跳转发生在Javascript =>引用之前(http://forum.jquery.com/topic/preventing-anchor-jump)

My solution is to position all anchors at the top by default with CSS.

我的解决方案是使用CSS将所有锚点放置在顶部。

.scroll-target{position:fixed;top:0;left:0;}

Then use jquery to scroll to the parent of the target anchor, or a sibling(maybe an empty em tag)

然后使用jquery滚动到目标锚或兄弟锚的父锚(可能是一个空的em标记)

<a class="scroll-target" name="section3"></a><em>&nbsp</em>

jquery example for scrolling for when URL is entered with hash
(page must not be already loaded in window/tab, this covers links from other/outside sources)

使用哈希输入URL时滚动的jquery示例(页面不能在window/tab中加载,它包含来自其他/外部源的链接)

setTimeout(function() {
    if (window.location.hash) {               
        var hash = window.location.hash.substr(1);   
        var scrollPos = $('.scroll-target[name="'+hash+'"]').siblings('em').offset().top; 
        $("html, body").animate({ scrollTop: scrollPos }, 1000);    
    }
}, 1);

Also you'll want to prevent default for anchor clicks while on the page and then scroll to their targets

此外,您还希望在页面上防止锚点单击的默认值,然后滚动到它们的目标

<a class="scroll-to" href="#section3">section three</a>

and jquery

和jquery

$('a.scroll-to').click(function(){
    var target = $(this).attr('href').substr(1);
    var scrollPos = $('.scroll-target[name="'+target+'"]').siblings('em').offset().top; 
    $("html, body").animate({ scrollTop: scrollPos }, 1000);
    return false;
});

The good thing about this method is the anchor tag targets, remain structurally beside the relevant content, although their CSS position is at the top.

This should mean that search engine crawlers won't have a problem.

Cheers, I hope this helps
Gray

这个方法的好处是锚标记目标在结构上保持在相关内容的旁边,尽管它们的CSS位置在顶部。这应该意味着搜索引擎爬虫不会有问题。干杯,我希望这能帮助格雷。

#13


0  

Try this to prevent client from any kind of vertical scrolling on hashchanged (inside your event handler):

尝试这样做,以防止客户端在hashchanged(在事件处理程序内部)上进行任何类型的垂直滚动:

var sct = document.body.scrollTop;
document.location.hash = '#next'; // or other manipulation
document.body.scrollTop = sct;

(browser redraw)

(浏览器重绘)

#14


0  

Solved my promlem by doing this:

解决了我的承诺:

// navbar height 
var navHeigth = $('nav.navbar').height();    

// Scroll to anchor function
var scrollToAnchor = function(hash) {
  // If got a hash
  if (hash) {
    // Scroll to the top (prevention for Chrome)
    window.scrollTo(0, 0);
    // Anchor element
    var term = $(hash);

    // If element with hash id is defined
    if (term) {

      // Get top offset, including header height
      var scrollto = term.offset().top - navHeigth;

      // Capture id value
      var id = term.attr('id');
      // Capture name value
      var name = term.attr('name');

      // Remove attributes for FF scroll prevention
      term.removeAttr('id').removeAttr('name');
      // Scroll to element
      $('html, body').animate({scrollTop:scrollto}, 0);

      // Returning id and name after .5sec for the next scroll
      setTimeout(function() {
        term.attr('id', id).attr('name', name);
      }, 500);
    }
  }
};

// if we are opening the page by url
if (location.hash) {
  scrollToAnchor(location.hash);
}

// preventing default click on links with an anchor
$('a[href*="#"]').click(function(e) {
  e.preventDefault();
  // hash value
  var hash = this.href.substr(this.href.indexOf("#"));
  scrollToAnchor(hash);
});`

#1


124  

Does your fix not work? I'm not sure if I understand the question correctly - do you have a demo page? You could try:

你的修复没有效果吗?我不确定我是否正确地理解了这个问题——你有演示页面吗?你可以试试:

if (location.hash) {
  setTimeout(function() {

    window.scrollTo(0, 0);
  }, 1);
}

Edit: tested and works in Firefox, IE & Chrome on Windows.
Edit 2: move setTimeout() inside if block, props @vsync.

编辑:在Firefox、IE和Chrome中测试和工作。编辑2:移动setTimeout(),如果block,道具@vsync。

#2


25  

See my answer here: * Answer

看我的回答:*回答

The trick is to just remove the hashtag ASAP and store its value for your own use:

窍门是尽快移除hashtag,并将其值存储到您自己的使用中:

It is important that you do not put that part of the code in the $() or $(window).load() functions as it would be to late and the browser already have moved to the tag.

重要的是,不要将代码的这一部分放在$()或$(窗口).load()函数中,因为它会延迟,浏览器已经移动到标记中。

// store the hash (DON'T put this code inside the $() function, it has to be executed 
// right away before the browser can start scrolling!
var target = window.location.hash,
    target = target.replace('#', '');

// delete hash so the page won't scroll to it
window.location.hash = "";

// now whenever you are ready do whatever you want
// (in this case I use jQuery to scroll to the tag after the page has loaded)
$(window).on('load', function() {
    if (target) {
        $('html, body').animate({
            scrollTop: $("#" + target).offset().top
        }, 700, 'swing', function () {});
    }
});

#3


11  

There are other ways of tracking what tab you're on; perhaps setting a cookie, or a value in a hidden field, etc etc.

还有其他方法可以跟踪你的标签;可能设置一个cookie,或者在隐藏字段中设置一个值,等等。

I would say that if you don't want the page jumping on load, you would be better off using one of these other options rather than the hash, because the main reason for using the hash in preference to them is to allow exactly what you're wanting to block.

我想说的是,如果你不想让页面加载,你最好使用其他选项而不是哈希,因为优先使用哈希的主要原因是允许你想要阻塞的东西。

Another point - the page won't jump if your hash links don't match the names of the tags in the document, so perhaps if you want to keep using the hash you could manipulate the content so that the tags are named differently. If you use a consistent prefix, you will still be able to use Javascript to jump between then.

另一点——如果您的散列链接与文档中标记的名称不匹配,页面不会跳转,因此,如果您希望继续使用散列,您可以对内容进行操作,以便以不同的方式命名标记。如果您使用一致的前缀,那么您仍然可以使用Javascript来跳转。

Hope that helps.

希望有帮助。

#4


10  

I used dave1010's solution, but it was a bit jumpy when I put it inside the $().ready function. So I did this: (not inside the $().ready)

我使用了dave1010的解决方案,但是当我把它放入$()时,它有点紧张。准备功能。所以我这样做了:(不在$().ready中)

    if (location.hash) {               // do the test straight away
        window.scrollTo(0, 0);         // execute it straight away
        setTimeout(function() {
            window.scrollTo(0, 0);     // run it a bit later also for browser compatibility
        }, 1);
    }

#5


8  

  1. Browser jumps to <element id="abc" /> if there are http://site.com/#abc hash in the address and the element with id="abc" is visible. So, you just should hide the element by default: <element id="anchor" style="display: none" />. If there is no visible element with id=hash at the page, the browser would not jump.

    如果地址中有http://site.com/#abc散列,并且id="abc"的元素是可见的,浏览器将跳转到 。因此,您应该默认隐藏元素: 。如果页面上没有id=hash的可见元素,浏览器将不会跳转。

  2. Create a script that checks the hash in url, and then finds and shows the prrpopriate element (that is hidden by default).

    创建一个脚本检查url中的散列,然后查找并显示prrpopriate元素(默认情况下是隐藏的)。

  3. Disable default "hash-like link" behaviour by binding an onclick event to a link and specify return false; as a result of onclick event.

    通过将onclick事件绑定到链接并指定返回false,禁用默认的“hashlink”行为。作为onclick事件的结果。

When I implemented tabs, I wrote something like that:

当我实现标签时,我写了这样的东西:

    <script>
    $(function () {         
        if (location.hash != "") {
            selectPersonalTab(location.hash);
        }
        else {
            selectPersonalTab("#cards");
        }
    });

    function selectPersonalTab(hash) {
        $("#personal li").removeClass("active");
        $("a[href$=" + hash + "]").closest("li").addClass("active");
        $("#personaldata > div").hide();
        location.hash = hash;
        $(hash).show();
    }

    $("#personal li a").click(function (e) {
        var t = e.target;
        if (t.href.indexOf("#") != -1) {
            var hash = t.href.substr(t.href.indexOf("#"));
            selectPersonalTab(hash);
            return false;
        }
    });
</script>

#6


2  

While the accepted answer does work well, I did find that sometimes, especially on pages containing large images that the scroll bar will jump about wildly using

虽然公认的答案确实有效,但我确实发现,有时候,特别是在包含大图片的页面上,滚动条会疯狂地使用这些图片

 window.scrollTo(0, 0);

Which can be quite distracting for the user.

这会让用户分心。

The solution I settled on in the end is actually pretty simple, and that's to use a different ID on the target to the one used in location.hash

我最后确定的解决方案实际上非常简单,那就是在目标上使用与location.hash中使用的ID不同的ID

Eg:

例如:

Here is the link on some other page

这是另一个页面的链接

<a href="/page/with/tabs#tab2">Some info found in tab2 on tabs page</a>

So of course if there is an element with an ID of tab2 on the tabs page the window will jump to it on load.

当然,如果标签页上有一个ID为tab2的元素,窗口会在加载时跳转到它。

So you can append something to the ID to prevent it:

所以你可以在ID上添加一些东西来防止它:

<div id="tab2-noScroll">tab2 content</div>

And then you can append "-noScroll" to location.hash in the javascript:

然后你可以附加“-noScroll”到位置。javascript的散列:

<script type="text/javascript">
    $(function() {

        var tabContent = $(".tab_content");
        var tabs = $("#menu li");
        var hash = window.location.hash;


     tabContent.not(hash + '-noScroll').hide();                           
        if(hash=="") {       //^ here
      $('#tab1-noScroll').fadeIn();
     }
        tabs.find('[href=' + hash + ']').parent().addClass('active');

        tabs.click(function() {
            $(this).addClass('active').siblings().removeClass('active');
            tabContent.hide();
            var activeTab = $(this).find("a").attr("href") + '-noScroll'; 
                                                               //^ and here

            $(activeTab).fadeIn();
           return false;
        });

    });
</script>

#7


2  

dirty CSS only fix to stay scrolled up every time the anchor is used (not useful if you still want to use anchors for scroll-jumps, very useful for deeplinking):

脏CSS只会在每次使用锚点时保持滚动(如果您仍然想要使用锚点进行滚动跳转,这对深度链接非常有用):

.elementsWithAnchorIds::before {
   content: "";
   display: block;
   height: 9999px;
   margin-top: -9999px; //higher thin page height
}

#8


1  

I think I've found a way for UI Tabs without redoing the functionality. So far I haven't found any problems.

我想我找到了一种不用重做功能的UI选项卡的方法。到目前为止我还没有发现任何问题。

    $( ".tabs" ).tabs();
    $( ".tabs" ).not(".noHash").bind("tabsshow", function(event, ui) { 
        window.location.hash = "tab_"+ui.tab.hash.replace(/#/,"");
        return false;
    });

    var selectedTabHash = window.location.hash.replace(/tab_/,"");
    var index = $( ".tabs li a" ).index($(".tabs li a[href='"+selectedTabHash+"']"));
    $( ".tabs" ).not(".noHash").tabs('select', index);

All within a ready event. It prepends "tab_" for the hash but work both when clicked and page loaded with hash.

一切都在准备就绪的情况下。它为散列预先写“tab_”,但在单击时和页面加载散列时都可以工作。

#9


1  

None of answers do not work good enough for me, I see page jumping to anchor and then to top for some solutions, some answers do not work at all, may be things changed for years. Hope my function will help to someone.

没有一个答案对我来说不够好,我看到page跳转到锚点,然后到顶部的一些解决方案,有些答案根本不起作用,可能事情会改变很多年。希望我的功能对某人有所帮助。

/**
 * Prevent automatic scrolling of page to anchor by browser after loading of page.
 * Do not call this function in $(...) or $(window).on('load', ...),
 * it should be called earlier, as soon as possible.
 */
function preventAnchorScroll() {
    var scrollToTop = function () {
        $(window).scrollTop(0);
    };
    if (window.location.hash) {
        // handler is executed at most once
        $(window).one('scroll', scrollToTop);
    }

    // make sure to release scroll 1 second after document readiness
    // to avoid negative UX
    $(function () {
        setTimeout(
            function () {
                $(window).off('scroll', scrollToTop);
            },
            1000
        );
    });
}

#10


0  

Another approach

Try checking if the page has been scrolled and only then reset position:

检查页面是否已滚动,然后重新设置位置:

var scrolled = false;

$(window).scroll(function(){
  scrolled = true;
});

if ( window.location.hash && scrolled ) {
  $(window).scrollTop( 0 );
}

Heres a demo

这是一个演示

#11


0  

I did not have much success with the above setTimeout methods in Firefox.

在Firefox中,在上面的setTimeout方法中,我没有取得多少成功。

Instead of a setTimeout, I've used an onload function:

我使用了onload函数,而不是setTimeout:

window.onload = function () {
    if (location.hash) {
        window.scrollTo(0, 0);
    }
};

It's still very glitchy, unfortunately.

不幸的是,它仍然很有光泽。

#12


0  

I have not had any consistent success with these solutions.

我在这些解决方案上没有取得任何一致的成功。

Apparently due to the fact that the jump happens before Javascript => reference(http://forum.jquery.com/topic/preventing-anchor-jump)

显然,这是因为跳转发生在Javascript =>引用之前(http://forum.jquery.com/topic/preventing-anchor-jump)

My solution is to position all anchors at the top by default with CSS.

我的解决方案是使用CSS将所有锚点放置在顶部。

.scroll-target{position:fixed;top:0;left:0;}

Then use jquery to scroll to the parent of the target anchor, or a sibling(maybe an empty em tag)

然后使用jquery滚动到目标锚或兄弟锚的父锚(可能是一个空的em标记)

<a class="scroll-target" name="section3"></a><em>&nbsp</em>

jquery example for scrolling for when URL is entered with hash
(page must not be already loaded in window/tab, this covers links from other/outside sources)

使用哈希输入URL时滚动的jquery示例(页面不能在window/tab中加载,它包含来自其他/外部源的链接)

setTimeout(function() {
    if (window.location.hash) {               
        var hash = window.location.hash.substr(1);   
        var scrollPos = $('.scroll-target[name="'+hash+'"]').siblings('em').offset().top; 
        $("html, body").animate({ scrollTop: scrollPos }, 1000);    
    }
}, 1);

Also you'll want to prevent default for anchor clicks while on the page and then scroll to their targets

此外,您还希望在页面上防止锚点单击的默认值,然后滚动到它们的目标

<a class="scroll-to" href="#section3">section three</a>

and jquery

和jquery

$('a.scroll-to').click(function(){
    var target = $(this).attr('href').substr(1);
    var scrollPos = $('.scroll-target[name="'+target+'"]').siblings('em').offset().top; 
    $("html, body").animate({ scrollTop: scrollPos }, 1000);
    return false;
});

The good thing about this method is the anchor tag targets, remain structurally beside the relevant content, although their CSS position is at the top.

This should mean that search engine crawlers won't have a problem.

Cheers, I hope this helps
Gray

这个方法的好处是锚标记目标在结构上保持在相关内容的旁边,尽管它们的CSS位置在顶部。这应该意味着搜索引擎爬虫不会有问题。干杯,我希望这能帮助格雷。

#13


0  

Try this to prevent client from any kind of vertical scrolling on hashchanged (inside your event handler):

尝试这样做,以防止客户端在hashchanged(在事件处理程序内部)上进行任何类型的垂直滚动:

var sct = document.body.scrollTop;
document.location.hash = '#next'; // or other manipulation
document.body.scrollTop = sct;

(browser redraw)

(浏览器重绘)

#14


0  

Solved my promlem by doing this:

解决了我的承诺:

// navbar height 
var navHeigth = $('nav.navbar').height();    

// Scroll to anchor function
var scrollToAnchor = function(hash) {
  // If got a hash
  if (hash) {
    // Scroll to the top (prevention for Chrome)
    window.scrollTo(0, 0);
    // Anchor element
    var term = $(hash);

    // If element with hash id is defined
    if (term) {

      // Get top offset, including header height
      var scrollto = term.offset().top - navHeigth;

      // Capture id value
      var id = term.attr('id');
      // Capture name value
      var name = term.attr('name');

      // Remove attributes for FF scroll prevention
      term.removeAttr('id').removeAttr('name');
      // Scroll to element
      $('html, body').animate({scrollTop:scrollto}, 0);

      // Returning id and name after .5sec for the next scroll
      setTimeout(function() {
        term.attr('id', id).attr('name', name);
      }, 500);
    }
  }
};

// if we are opening the page by url
if (location.hash) {
  scrollToAnchor(location.hash);
}

// preventing default click on links with an anchor
$('a[href*="#"]').click(function(e) {
  e.preventDefault();
  // hash value
  var hash = this.href.substr(this.href.indexOf("#"));
  scrollToAnchor(hash);
});`