【问题标题】:Add scrolling effect to all anchors except of one为除一个之外的所有锚添加滚动效果
【发布时间】:2016-07-04 20:25:47
【问题描述】:

我有一个包含一些菜单项的菜单。所有这些都是这样定义的:

<li><a href="#about" target="_self" title="about">About</a></li>

链接到 pdf 的除外:

<li><a href="pdf/theDocument.pdf" target="_blank">My Pdf</a></li>

现在我想在我的页面上添加一些平滑滚动,当点击链接到 pdf 的锚点除了。我有以下 jQuery 代码,它添加了滚动效果,但禁用了在新选项卡中打开 pdf 文件。这是我实现滚动的代码。

$(document).on('click', 'a', function(event){
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 700);
});

任何想法如何为除链接 pdf 的锚之外的所有锚添加滚动效果吗?谢谢!

【问题讨论】:

  • 您可以在点击事件中使用if ($(this).attr("href") == "pdf/theDocument.pdf")

标签: javascript jquery html pdf anchor


【解决方案1】:

您可以使用:not() Selector 选择除具有target="_blank" a:not([target="_blank"]) 的元素之外的所有元素,或选择除具有href starts with 的元素之外的所有元素 pdf 'a:not([href^="pdf"])'

$(document).on('click', 'a:not([target="_blank"])', function(event){
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 700);
});

【讨论】:

    【解决方案2】:

    您可以在此链接中添加一个 id,然后在您的代码中:

    <li><a href="pdf/theDocument.pdf" id="pdfId" target="_blank">My Pdf</a>
    

    然后:

    $(document).on('click', 'a', function(event){
    
        if (event.target.id === 'pdfId') {
           return;
        }
    
        event.preventDefault();
    
        $('html, body').animate({
            scrollTop: $( $.attr(this, 'href') ).offset().top
        }, 700);
    });
    

    【讨论】:

      【解决方案3】:

      为您希望平滑滚动发生的所有锚点添加一个类

      $(document).on('click', '.classYouAdded', function(event){
          event.preventDefault();
      
          $('html, body').animate({
              scrollTop: $( $.attr(this, 'href') ).offset().top
          }, 700);
      });
      

      【讨论】:

        猜你喜欢
        • 2014-11-09
        • 1970-01-01
        • 1970-01-01
        • 2015-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-08
        • 2018-04-17
        相关资源
        最近更新 更多