我有一个带有 anchor 的平滑滚动,它的工作非常完美。但是这个JS和我用的插件有冲突,所以我需要改脚本。
我想要的不是 anchor ,而是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 而不是链接时,可以使用数据属性来提供 anchor 信息。标记看起来像这样:
<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
标签不再需要平滑地滚动到页面上的 anchor 。现在可以正常使用指向外部页面和 anchor 的链接,而不会以任何方式与原始脚本发生冲突。
关于javascript - 平滑滚动 div 到 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33093341/