是否可以滚动到Chrome中页面加载时从url hash获取id的元素?我用Google搜索并尝试了所有内容,但Chrome似乎没有任何效果。例如,以下代码在Safari中有效,但在Chrome中无效:
$(window).load(function() {
if(location.hash) {
var target = location.hash;
location.hash = '';
$('html,body').animate({scrollTop: $(target).offset().top + 'px'}, 300);
}
});
尝试运行这一个:)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").scroll(function(){
location.hash = "part5";
alert(location.hash)
});
});
</script>
</head>
<body>
<p>Try the scrollbar in the div</p>
<div style="border:1px solid black;width:200px;height:100px;overflow:scroll;">In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
<br><br>
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'
</div>
<p>Scrolled <span>0</span> times.</p>
</body>
</html>
首先,你必须使用window.location.hash
而不仅仅是location.hash
。这是工作片段,我已经在Chrome中测试过(示例没有window.location.hash
,只是滚动):
$(window).load(function() {
$('html, body').animate({
scrollTop: $("#elementToScroll").offset().top
}, 2000);
});
.regular {
width: 100%;
height: 500px;
background-color: blue;
border: 5px black solid;
margin: 16px;
}
#elementToScroll {
width: 100%;
height: 500px;
background-color: yellow;
border: 5px black solid;
margin: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="regular"></div>
<div class="regular"></div>
<div class="regular"></div>
<div id="elementToScroll"></div>
这里:
$(selector).animate({
scrollTop: value
}, time);
我们是动画scrollTop
方法,在这里:
$(element).offset().top
我们正在从页面顶部获取元素的偏移量。
Chrome会在页面加载前尝试滚动,因此我在窗口加载函数中使用超时功能解决了问题。不确定它是否是最佳解决方案,但它确实有效。
setTimeout(function(){
$("html, body").animate({
scrollTop: $(target).offset().top}, 300);
}, 1000);
Chrome中的问题是,当DOMContentLoaded
是document.readyState
时,interactive
会被解雇,但是在那个时候,它无法以编程方式滚动。虽然超时可能会起作用,但取决于它的持续时间和加载速度,这是一个万无一失的解决方案:
let callback = () => {
if (document.readyState === 'complete') {
$(selector).animate({
scrollTop: value
}, time);
}
};
if (document.readyState === 'complete') {
callback();
} else {
document.addEventListener('readystatechange', callback);
}
在这个片段中,立即检查readyState
,如果它已经是complete
,则立即调用回调,否则,我们将一个eventlistener添加到readystatechange
事件并在readyState
为complete
时调用回调。