代码之家  ›  专栏  ›  技术社区  ›  ptts

在shopify站点中未定义滚动顶部

  •  1
  • ptts  · 技术社区  · 7 年前

    我在一家电子商务商店(shopify/liquid)工作。

    现在因为这是一个CMS,我不得不通过编辑器或者用JS手动添加一些属性。

    这里我给它一个

    $(document).ready(function() {
        $(".hero__cta").addClass("scroll");
        $(".hero__cta").attr("href", "#section2")
    });
    

    如果你去网站,在主图像下,@the new entries@title,有这样的标记:

    <a id="section2"> </a>
    

    这里是JS函数:

    $(document).ready(function(){
        $("a").on('click', function(event) {
            if (this.hash !== "") {
                event.preventDefault();
                var hash = this.hash;
                $('html, body').animate({scrollTop: $(hash).offset().top}, 800,
                    function() {                
                    window.location.hash = hash;
                    }
                );
            }
        });
    });
    

    因此,如果您转到站点并单击CTA按钮,它应该平滑滚动到该锚。在代码笔等上工作,但在Shopify平台上不工作。

    Uncaught TypeError:无法读取未定义的属性“top”

    现场直播:

    https://www.toptrendshopping.com/

    哦,我该如何在哪里添加IntersectionObserver polifill?

    1 回复  |  直到 7 年前
        1
  •  0
  •   ptts    7 年前

    我找到了解决办法。正如你所看到的,这项工作现在在现场。

    $(document).ready(function(){
    $(".hero__cta").attr("href", "#two");
    $('a[href*="#"]')
    // Remove links that don't actually link to anything
      .not('[href="#"]')
     .not('[href="#0"]')
     .click(function(event) {
        // On-page links
         if (
         location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
        && 
        location.hostname == this.hostname
         ) {
         // Figure out element to scroll to
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
         // Does a scroll target exist?
        if (target.length) {
         // Only prevent default if animation is actually gonna happen
          event.preventDefault();
         $('html, body').animate({
          scrollTop: target.offset().top
          }, 1000, function() {
          // Callback after animation
          // Must change focus!
           var $target = $(target);
           $target.focus();
           if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
           };
         });
        }
    }
    

    });

    另外,如果你想在shoppify商店中添加polyfill,可以在主题.液体“文件。