简体   繁体   中英

Scroll to anchor after opening fancybox

i have realized a "help"-view in a fancybox. In this fancybox i've got a navigation menue. This menue works with anchor links. So far so good.

Now i want to open this fancybox and directly scroll to a spezific anchor. Here my code, how i open the fancybox:

    $.fancybox({
       width       : 1000,
       height      : 800,
       minHeight   : 800,
       maxHeight   : 800,               
       minWidth    : 1000,
       maxWidth    : 1000,
       fitToView   : false,
       autoSize    : true,
       closeClick  : false,
       openEffect  : 'none',
       closeEffect : 'none',
       scrolling   : 'yes',
       href        : "#idofview",
   })

I tried a few things, but nothing works. I tried:

location.href = "#anchor";
//or
location.hash = "#anchor";
//or
afterShow: function() {
    $(this).closest('.fancybox-inner').animate({
            scrollTop: $('.fancybox-overlay').scrollTop() + $("#anchorid").offset().top
        });
//or
$(document.body).scrollTop($('#anchorid').offset().top);

I also tried to trigger the click of my anchor link:

$("#btn_link").trigger('click');

Is there any reason to direktly scroll to the anchor in a fancybox?

You may need to find the offset().top of your targeted anchor first, then just animate the .fancybox-inner selector to that position (you don't need this $(this).closest() method at all) so :

jQuery(document).ready(function ($) {
    $(".fancybox").fancybox({
        // API options
        afterShow: function () {
            var toScroll = $(".fancybox-inner").find("#anchor2").offset().top - 35;
            $(".fancybox-inner").animate({
                scrollTop: toScroll
            }, 1000);
        }
    }); // fancybox
}); // ready

Notice that I am subtracting 35px from the offset (in var toScroll ) because the fancybox's padding , but this is a variable you may need to play with.

See JSFIDDLE

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