Javascript jQuery自动从不同页面滚动到ID
我在stackoverflow上看到过这个问题,但是在那里使用的代码不同,我没有真正理解它。所以我想让网站滚动到div时,网站是从另一个页面Javascript jQuery自动从不同页面滚动到ID,javascript,jquery,html,Javascript,Jquery,Html,我在stackoverflow上看到过这个问题,但是在那里使用的代码不同,我没有真正理解它。所以我想让网站滚动到div时,网站是从另一个页面 $(document).ready(function(){ // Add smooth scrolling to all links $("a").on('click', function(event) { // Make sure this.hash has a value before overriding default behav
$(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 -70
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
此代码在主页中工作,滚动平滑,但在从其他页面单击时不工作。加载页面时,此代码将滚动正文至
#someDiv
顶部偏移:
$(document).ready(function(){
$('html, body').animate({
scrollTop: $('#someDiv').offset().top - 70
}, 800);
});
如果推荐人
不是http://www.example.com
:
$(document).ready(function(){
if (document.referrer !== "http://www.example.com") {
$('html, body').animate({
scrollTop: $('#someDiv').offset().top - 70
}, 800);
}
});
这是来自另一页的信息:
$(document).ready(function(){
if(document.referrer != '' && document.referrer != location.href ){
$('html, body').animate({
scrollTop: $('#someDiv').offset().top - 70
}, 800);
}
});
你找到的那篇文章的链接是什么?这不起作用的原因是您单击转到另一个页面,该页面将再次呈现此脚本,但不会触发滚动,因为所有内容都在您的单击处理程序中。