【问题标题】:Extract hash or page提取哈希或页面
【发布时间】:2019-03-20 04:46:29
【问题描述】:

我需要编辑下面的代码。现在它适用于 url (www.mypage.com/#contact) 中的锚点。我需要根据以下示例修改此代码以保存到 var target 变量中:

www.mypage.com/#contact > 目标 = 联系人

www.mypage.com/page.html > 目标 = 页面

www.mypage.com/page.html#contact > 目标 = 联系人

$('a.js-scroll-trigger[href*="#"]').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: (target.offset().top - 70)
        }, 1000, "easeInOutExpo");
        return false;
      }
    }
});

感谢您的帮助。

【问题讨论】:

  • 怎么样:www.mypage.com and www.mypage.com/target and www.mypage.com/target/ and www.mypage.com# and www.mypage.com/# and www.mypage.com/page.html#?
  • 有什么问题?

标签: jquery url hash


【解决方案1】:

在下面的示例中,我定义了一个包含hash(不带“#”)或pathname(不带文件扩展名)的变量。然后,测试结果值是否存在具有 idname 的元素。如果一个元素存在,滚动到它。

$('a.js-scroll-trigger').click(function(e) {
  e.preventDefault();

  // get the hash (without #) or filename (without extension)
  var s = this.hash.substr(1) || this.pathname.match(/([^\/]+)(?=\.\w+$)/)[0];
  console.log(s);

  // test for an existing element that has matching ID or NAME.
  var $target = $("#" + s).length ? $("#" + s) : $('[name=' + s + ']');

  // if that element exists, scroll to it
  if ($target.length) {
    $('html, body').animate({
      scrollTop: ($target.offset().top - 70)
    }, 1000);
  }

});
a {
  display: block;
}

#contents {
  margin-top: 150vh;
}

#contents div {
  height: 100vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a class="js-scroll-trigger" href="https://www.mypage.com/#contact">www.mypage.com/#contact</a>
<a class="js-scroll-trigger" href="https://www.mypage.com/page.html">www.mypage.com/page.html</a>
<a class="js-scroll-trigger" href="https://www.mypage.com/page.html#contact">www.mypage.com/page.html#contact</a>

<div id="contents">
  <div id="contact">
    CONTACT
  </div>
  <div name="page">
    PAGE
  </div>
</div>

【讨论】:

  • 谢谢。您的代码和 data-href i 菜单解决了我的问题。
猜你喜欢
  • 2012-02-19
  • 2011-07-31
  • 2011-06-05
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
  • 2014-12-03
  • 1970-01-01
相关资源
最近更新 更多