简体   繁体   English

URL href失败:锚点,URL和Javascript

[英]URL href failing: Anchors, URL, and Javascript

I am using javascript for smooth scrolling (in script tags below) and also have href for anchor links. 我正在使用javascript进行平滑滚动(在下面的脚本标签中),并且还具有href的锚链接。 All of the anchors are working fine but the javascript appears to be disabling the href for the URL. 所有锚点都可以正常工作,但是javascript似乎在禁用URL的href。 Can you help me rewrite this so that works as well? 您能帮我重写一下,使其也正常工作吗?

<ul class="snip1143">
    <li class><a href="#home1" data-hover="Home">Home</a></li>
    <li><a href="#about1" data-hover="About">About</a></li>
    <li><a href="#experience1" data-hover="Work">Work</a></li>
    <li><a href="URL HERE" data-hover="Blog">Blog</a>   </li
    <li><a href="#contact1" data-hover="Contact">Contact</a></li>

<script>

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

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

</script>

event.preventDefault() is going to prevent the default, which for anchors is going to that url. event.preventDefault()将防止使用默认值,对于锚来说,默认值将使用该URL。 You probably want to add a class to the anchors that you want to animate and select only those instead of preventing default on all anchor tags. 您可能想向要创建动画的锚添加一个类,并仅选择那些类,而不是阻止所有锚标记上的默认设置。

Acutally since you have unique data-hover for each element, all we have to do then is filter it by validating the value of their data-hover attribute. 由于每个元素都有唯一的data-hover ,因此,我们要做的就是通过验证其data-hover属性的值来对其进行过滤。

<script>

  $(document).on('click', 'a', function(event) {
      if($(this).data('hover') !== "Blog"){       
       $('html, body').animate({
          scrollTop: $( $.attr(this, 'href') ).offset().top
       }, 500);
    }// since i noticed that you want to redirect the page once the Blog link is clicked
  });

</script>

Let me know if this helps you with your problem. 让我知道这是否可以帮助您解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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