[英]Smooth scroll div to div
我有一個平滑的滾動與錨和它的工作完美。 但是這個JS與我使用的插件沖突,所以我需要更改腳本。
我想要的不是錨,我想使用div。 但我不知道怎么做。
注意:有一個href鏈接到不同的頁面。
這是我目前正在使用的腳本。
jQuery.noConflict();
jQuery(document).ready(function($){
$('a[href*=#]:not([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
}, 1000);
return false;
}
}
});
});
我需要的示例html(我不知道html的格式是否正確):
<div id="#test"></div>
<div id="test"></div>
更新:
這是以下答案的代碼
jQuery.noConflict();
jQuery(document).ready(function($){
$('[data-anchor]').click(function(){
var target = $($(this).data('anchor'));
if (target.length){
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
}
});
});
該代碼正常工作,但當div有一個指向另一個頁面的鏈接時,代碼無效。
示例html:
<div data-anchor="/testEnvironment/how-can-i-get-a-loan/#whocangetaloan"></div>
這個html是不同頁面的地方
<section id="#whocangetaloan"></section>
如果要使用div而不是鏈接,可以使用數據屬性來提供錨信息。 標記看起來像這樣:
<header>
<div id="menu">
<div data-anchor="#home">Home</div>
<div data-anchor="#about">About</div>
<div data-anchor="#services">Services</div>
<div data-anchor="#projects">Projects</div>
<div data-anchor="#contact">Contact</div>
</div>
</header>
<section id="home"></section>
<section id="about"></section>
<section id="services"></section>
<section id="projects"></section>
<section id="contact"></section>
然后這個腳本將實現動畫:
jQuery.noConflict();
jQuery(document).ready(function($) {
$('[data-anchor]').click(function() {
var target = $($(this).data('anchor'));
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
}
});
});
這將使a
標簽不再需要順利滾動到頁面上的一個錨。 現在可以正常使用外部頁面和錨點的鏈接,而原始腳本不會以任何方式發生沖突。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.