【问题标题】:Scroll top undefined in shopify site在shopify网站中滚动顶部未定义
【发布时间】:2019-02-01 21:31:47
【问题描述】:

我在电子商务商店(shopify/liuquid)工作。

我想平滑滚动到不同的哈希值。

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

这里我给它href

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

如果您访问该网站,在主图像下方,@新条目@标题,有这样的标记:

<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 按钮,它应该会平滑滚动到该锚点。适用于 Codepen 等,但不适用于 Shopify 平台。

我明白了:

未捕获的类型错误:无法读取未定义的属性“顶部” 在 HTMLAnchorElement。

该网站正在这里:

https://www.toptrendshopping.com/

哦,我该如何以及在哪里为此添加 IntersectionObserver polifill?

【问题讨论】:

  • 如果您尝试使用 jquery 绑定到动态创建的 HTML 元素,您将需要使用 this question 作为参考。
  • @MUlferts,这也不起作用,刚试过。
  • 如果我只是点击控制台登录,那可以,但仍然无法识别属性顶部
  • 对为什么要使用 jQuery 添加类有点困惑?为什么不能直接在 HTML 中添加?
  • @SamJohnson 我可以看到您熟悉 shopify API 和 Liquid。我已经通过 Jquery 添加了这些类,因为通过后端没有简单的方法。而且我不想在模板文件中进行太多更改(但将来会这样做)。无论如何,我想问你一些事情,我想将 ID 添加到下拉菜单中,以获得与 CTA btn 上相同的动画滚动。如果我在后端更改 URL,它将不起作用。 (如果你明白我的意思)。那么,如何为下拉 LI 分配 ID?我能想到的最好的方法是使用 queryselecor 或 css child ,然后分配 ID

标签: javascript jquery shopify liquid


【解决方案1】:

我找到了解决办法。如您所见,这现在可以在实时网站上使用。

$(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
       };
     });
    }
}

}); });

在 CSS 技巧上找到了这个,仍然不完全为什么所有这些都是必需的,但现在可以工作。

还有一点额外的,如果您想在 Shopify 商店中添加 polyfill,请在“theme.liquid”文件的头部执行。

【讨论】:

    猜你喜欢
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多