我需要编辑以下代码。现在,它适用于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;
}
}
});
感谢帮助。
答案 0 :(得分:0)
在下面的示例中,我定义了一个变量,其中包含hash
(不带“#”)或pathname
(不带文件扩展名)。然后,测试结果值是否存在与该id
或name
相同的元素。如果存在某个元素,请滚动到该元素。
$('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>