我遇到了一个问题,即在一个溢出的元素中顺利滚动。第一个链接/锚点按预期工作,但任何后续链接都不会滚动到它们的锚点。
小提琴:http://jsfiddle.net/BPyVd/1/
<!doctype html>
<html>
<head>
<style>
#container {width: 400px; height: 400px; background: #ccc; overflow-y: scroll}
div > div {margin-top: 500px; height: 1px; background: red;}
</style>
</head>
<body>
<div id="container">
<a href="#anchor-a">NEXT</a>
<div id="anchor-a"></div>
<a href="#anchor-b">NEXT</a>
<div id="anchor-b"></div>
<a href="#anchor-c">NEXT</a>
<div id="anchor-c"></div>
</div>
<script>
$(function() {
$('a').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) {
$('#container').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
</script>
</body>
</html>
任何帮助都不仅仅是值得赞赏的。谢谢。
答案 0 :(得分:4)
修正脚本:
<script>
$(function() {
$('a').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) {
$('#container').animate({
scrollTop: $('#container').scrollTop() + target.offset().top
}, 1000);
return false;
}
}
});
});
</script>