当元素动态包装为锚点时,平滑滚动或工作
问题描述:
对于移动设备,我想将所有h1
标题转换为可平滑滚动到其目标的锚点。为此,当发生某个设备调整大小时,我只需用a
标记包装h1
标记的内容,然后在设备回到桌面宽度时打开a
标记的内容。当元素动态包装为锚点时,平滑滚动或工作
$(document).ready(function() {
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
//the function to convert the heading to an anchor for devices smaller than 780px
function makeResponsive() {
if ($(window).width() < 780) {
if ($('a').length) {
return true;
} else {
$('h1').each(function() {
$(this).contents().eq(0).wrap('<a href="#section2"></a>');
});
}
} else {
$('a').contents().unwrap();
}
}
//run on document load and on window resize
$(document).ready(function() {
//on load
makeResponsive()
//on resize
$(window).resize(function() {
makeResponsive();
});
});
body,
html,
.main {
height: 100%;
}
section {
min-height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
The Heading
</h1>
<div class="main">
<section></section>
</div>
<div class="main" id="section2">
<section style="background-color:blue"></section>
</div>
的问题是,当H1的内容转换为锚,平滑滚动是不会发生的一切,锚正好跳到目标。
答
您的a-Tag没有得到单击事件,因为您在不存在侦听器时添加它。
试试这个
$(document).on('click', 'a', function(event) {...
答
而不是将它包装在锚点中,只需将“移动锚点”类添加到这些标题即可。然后,而不是听关于锚点击,监听对“移动锚”和变革点击:
$('html, body').animate({
scrollTop: $('#section2').offset().top
}, 800, function() {
甚至一个简单的解决方案 - 您对点击功能非常年底前,增加“返回false ;”所以浏览器不会自动向下滚动页面。
编辑:另外,将所有内容都包含在单个documentReady函数中,并在添加点击侦听器之前执行makeResponsive()。