Tocify在标题上方插入命名div。它使用哈希标记来导航和推送到历史记录。我们使用Tocify来定位溢出的div内容区域 - 它运行良好。
后退按钮更新哈希并触发事件,但滚动不执行 - 没有错误。与窗口加载事件中的哈希相同的逻辑按预期工作。
我错过了什么?
function scrollToAnchor(hash) {
alert("Scroll to: " + hash);
var dTag = $("div[name='" + hash + "']");
$('.topic').animate({ scrollTop: dTag.offset().top }, 'slow');
}
$(window).load(function () {
var hash = location.hash.replace('#', '');
if (hash != '') {
scrollToAnchor(hash);
}
});
if (window.history && window.history.pushState) {
$(window).on('popstate', function () {
var hash = location.hash.replace('#', '');
if (hash != '') {
scrollToAnchor(hash);
}
});
}
答案 0 :(得分:0)
如果主题有自己的滚动条,那么您的代码只会有用。要在元素内滚动:
var loaded = $.Deferred();
$(window).ready(function() {
var hash = location.hash.replace('#', '');
if (hash != '') {
scrollToAnchor(hash);
}
var offsets = [];
var item = function(key, value) {
return {
key: key,
value: value
};
};
offsets.push(new item('topic', $(".topic").offset().top));
$(".topic div").each(function(index, element) {
offsets.push(new item(element.getAttribute("name"), element.offsetTop));
});
loaded.resolve(offsets);
});
function scrollToAnchor(hash) {
var dTag = $("div[name='" + hash + "']");
// makes sure on window ready as ran
loaded.done(function(offsets) {
var grep = function(item) {
return $.grep(offsets, function(_item) {
return _item.key == item;
})[0].value;
};
$(".topic").animate({
scrollTop: grep(hash) - grep("topic")
}, 'slow');
});
}
if (window.history && window.history.pushState) {
$(window).on('popstate', function() {
var hash = location.hash.replace('#', '');
if (hash != '') {
scrollToAnchor(hash);
}
});
}
div {
height: 300px;
width: 200px;
border: 1px solid black;
}
.topic {
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#1">1</a>
<a href="#2">2</a>
<a href="#3">3</a>
<br>
<div class="topic">
<div name="1">
1
</div>
<div name="2">
2
</div>
<div name="3">
3
</div>
</div>
如果您不希望主题有滚动条
只需更改
function scrollToAnchor(hash) {
alert("Scroll to: " + hash);
var dTag = $("div[name='" + hash + "']");
$('.topic').animate({ scrollTop: dTag.offset().top }, 'slow');
}
到
function scrollToAnchor(hash) {
alert("Scroll to: " + hash);
var dTag = $("div[name='" + hash + "']");
$('window, body').animate({ scrollTop: dTag.offset().top }, 'slow');
}
<强>更新强>
我不确定在第一个版本中确实需要Deferred。我认为这个更简单的版本也可以正常工作。 jsfiddler