Javascript Jquery更改位置,然后滚动到元素
当我在index.php上并按下home按钮时,它会向下滚动到元素。但是,当我不在index.php上并按下相同的按钮时,我想更改URL位置,然后滚动到元素。我就是这样尝试的:Javascript Jquery更改位置,然后滚动到元素,javascript,jquery,Javascript,Jquery,当我在index.php上并按下home按钮时,它会向下滚动到元素。但是,当我不在index.php上并按下相同的按钮时,我想更改URL位置,然后滚动到元素。我就是这样尝试的: $('.home').on('click', function (event) { // If location is index.php do this: if (location.href.indexOf("/index.php") > -1) { $('html, body
$('.home').on('click', function (event) {
// If location is index.php do this:
if (location.href.indexOf("/index.php") > -1) {
$('html, body').animate({
scrollTop: $("#anotherelement").offset().top
}, 1000);
// If location is not index.php do this:
} else {
window.location = "index.php";
$('html, body').animate({
scrollTop: $("#anotherelement").offset().top
}, 1000);
}
});
它只是更改url,但当我不在索引上时,它不会滚动到元素。php使用哈希而不是使用jQuery滚动到某个元素
http://www.myurl.com/index.php#anotherelement
anotherelement
)请将您的代码更改为
$('.home').on('click', function (event) {
if (location.href.indexOf("/index.php") > -1) {
$('html, body').animate({
scrollTop: $("#anotherelement").offset().top
}, 1000);
} else {
window.location = "index.php#anotherelement";
}
});
当您更改加载新页面的位置时,您需要在dom ready函数上使用它(滚动效果),这样您的滚动代码就没有用了,因为您是从“上一页”开始执行的。这是正确的,但是没有任何动画。这可以在新加载的页面上使用
hashchange
事件来处理,但显然这符合OP的需要:)