我有一些带有内容的页面,底部有分页,如下图所示。
我想要做的是(平滑)滚动到 anchor 链接,如果访问者访问第二页、第三页等(例如www.example.com/list ?page=2
)
我想使用 URL 条件来执行此操作:检查 URL 是否包含“page”字符串,然后滚动到 anchor ,但它不起作用。
<script>
$(document).ready(function () {
var url = window.location.href;
if(url.indexOf("page") > -1) {
scrollTop( $("#anchor-link").offset().top );
}
});
</script>
我想知道,使用这样的方法(使用 JS 检查 URL 条件 并滚动)或使用 #anchor-link
附加每个分页链接是否更好(性能、跨浏览器等)我该怎么做?
最佳答案
假设您有一个页面,其中包含名为 mysection1
、mysection2
、... 的部分或页面
可以使用函数获取GET参数page
function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
然后,使用
滚动到特定部分$(document).ready(function() {
$('html, body').animate({
scrollTop: $( '#mysection' + page ).offset().top
}, 500);
});
演示
var page = findGetParameter('page');
if(page == undefined)
{
alert('No page');
page = 1;
}
$(document).ready(function() {
$('html, body').animate({
scrollTop: $( '#mysection' + page ).offset().top
}, 500);
});
function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
body { background-color: #000; color: #fff; }
a { color: aqua; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height: 1500px;"></div>
<div id="mysection1">Page 1</div>
<div style="height: 1500px;"></div>
<div id="mysection2">Page 2</div>
<div style="height: 1500px;"></div>
<div id="mysection3">Page 3</div>
<div style="height: 1500px;"></div>
<div id="mysection4">Page 4</div>
<div style="height: 1500px;"></div>
关于javascript - 如何根据 URL 条件滚动到 anchor ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40586206/