开发者

Can I get back to normal scroll-to-target behavior with asynchronous content?

开发者 https://www.devze.com 2023-04-10 02:52 出处:网络
I\'m loading content on demand on a webpage I\'m working on. For various reasons, I\'m also using the default browser behavior of scrolling to the :target fragment. You know, you click on a link that

I'm loading content on demand on a webpage I'm working on. For various reasons, I'm also using the default browser behavior of scrolling to the :target fragment. You know, you click on a link that looks like #abc and the browser scrolls to id="abc" in your page.

Except that's not exactly what happens when the content is made available asynchronously. According to my test page, you have to click the link twice in order to have the the browser scroll to the asynchronously-added e开发者_C百科lement or the CSS3 :target selector select it. So what I can do about it so that my users don't have to click twice?


Add a callback function to .load, which scrolls to the just-added element.

$(document).ready(function () {
   "use strict";
   $("a[href=#loadme]").click(function () {
       if ("testcomplete" in window && window.testcomplete) {
            return;
       }
       $("#loadhere").load("loadme.inc", function(){
            location.href = this.href;
            //Your method to scroll "for various reasons"
       });
       window.testcomplete = true;
       return true; //Prevent default behaviour, ie following the `href` target
   })
})
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号