本文介绍了Jquery更改位置然后滚动到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将哈希添加到URL www.myurl/index.php#anotherelement 在要在页面加载时滚动的页面中添加具有相同ID的元素(在此示例中为 anotherelement )。
Add the hash to the URL www.myurl/index.php#anotherelement
Add the element with the same id(anotherelement in this example) in the page where you want to scroll on page load.
当我在index.php上并按下主页按钮时,它向下滚动到元素。但是,当我不在index.php上并按下相同的按钮时,我想更改URL位置,然后滚动到该元素。这就是我尝试的方式:
When I am on the index.php and press the home button, it scroll down to the element. However, when I'm not on the index.php and press the same button, I want to change the URL location, then scroll to the element. This is how I tried:
$('.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); } });它只是更改了网址但是当我不在索引时它不会滚动到元素.php
It just changes the url but it doesn't scroll to element when I'm not on the index.php
推荐答案使用hash而不是使用jQuery滚动到某个元素。
Use hash instead of using jQuery to scroll to some element.
更多推荐
Jquery更改位置然后滚动到元素
发布评论