简体   繁体   中英

Anchor link to content inside hidden div

I'm trying to link to content from an external page, using

<a name="anchor"></a>

and

<a href="/somepage/#anchor"></a>

The content where the anchor is located is hidden inside a drawer, using jQuery:

$(".toggle_container").hide();

See fiddle: http://jsfiddle.net/bd1mbu5j/1/

I've tried wrapping my head around the method found here , but I know there's something I'm missing.

window.onload = function() {
    var hash = window.location.hash; // would be "#div1" or something
    if(hash != "") {
        var id = hash.substr(1); // get rid of #
        document.getElementById(id).style.display = 'block';
    }
};

Also should be noted, I'm not just trying to open the drawer, but link to specific content within certain drawers.

See this fiddle http://jsfiddle.net/bd1mbu5j/2/

  $(".toggle_container").hide();
  $("h3.trigger").click(function(){
    var _this = this;
    $(this).toggleClass("active").next().slideToggle("normal", function () {
        var anchor = $(_this).data('anchor');
        console.log(anchor);

        if (anchor && $('#'+anchor).length) {
            console.log($('#'+anchor).offset().top);
            $('html, body').animate({scrollTop: $('#'+anchor).offset().top+'px'});
        }
    });

    return false; //Prevent the browser jump to the link anchor
  });

I added the target element id as a data attribute and picked that up once the slide toggle was finished. Then I animated down to that element if it exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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