Javascript 如何根据URL条件滚动到锚点?
我有一些页面,底部有内容和页码,如下图所示 如果访问者访问第二页、第三页等(例如Javascript 如何根据URL条件滚动到锚点?,javascript,jquery,anchor,Javascript,Jquery,Anchor,我有一些页面,底部有内容和页码,如下图所示 如果访问者访问第二页、第三页等(例如www.example.com/list?page=2),我想做的是(平滑)滚动到锚定链接 我想用一个URL条件来实现这一点:检查URL是否有“page”字符串,然后滚动到锚点,但它不起作用 <script> $(document).ready(function () { var url = window.location.href; if(url.indexOf
www.example.com/list?page=2
),我想做的是(平滑)滚动到锚定链接
我想用一个URL条件来实现这一点:检查URL是否有“page”字符串,然后滚动到锚点,但它不起作用
<script>
$(document).ready(function () {
var url = window.location.href;
if(url.indexOf("page") > -1) {
scrollTop( $("#anchor-link").offset().top );
}
});
</script>
$(文档).ready(函数(){
var url=window.location.href;
如果(url.indexOf(“页面”)>-1){
scrollTop($(“#锚定链接”).offset().top);
}
});
我想知道,如果使用这样的方法(用JS和scroll检查URL条件)或用
#锚定链接附加每个分页链接(性能、跨浏览器等)是否更好,我该如何做呢?假设您有一个名为mysection1
,mysection2
您可以使用函数获取get参数页面
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');
如果(第==页未定义)
{
警报(“无页面”);
page=1;
}
$(文档).ready(函数(){
$('html,body')。设置动画({
scrollTop:$('#mysection'+page).offset().top
}, 500);
});
函数findGetParameter(parameterName){
var result=null,
tmp=[];
location.search
.R(1)
.分割(&)
.forEach(功能(项目){
tmp=项目拆分(“=”);
如果(tmp[0]===parameterName)结果=decodeURIComponent(tmp[1]);
});
返回结果;
}
body{背景色:#000;颜色:#fff;}
a{color:aqua;}
第1页
第2页
第3页
第4页
假设您有一个包含名为mysection1
,mysection2
您可以使用函数获取get参数页面
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');
如果(第==页未定义)
{
警报(“无页面”);
page=1;
}
$(文档).ready(函数(){
$('html,body')。设置动画({
scrollTop:$('#mysection'+page).offset().top
}, 500);
});
函数findGetParameter(parameterName){
var result=null,
tmp=[];
location.search
.R(1)
.分割(&)
.forEach(功能(项目){
tmp=项目拆分(“=”);
如果(tmp[0]===parameterName)结果=decodeURIComponent(tmp[1]);
});
返回结果;
}
body{背景色:#000;颜色:#fff;}
a{color:aqua;}
第1页
第2页
第3页
第4页
(scrollTop($(“#锚定链接”).offset().top);
-看起来像是一个额外的大括号?是的,它应该是scrollTop($(“#锚定链接”).offset().top);
(scrollTop($(“#锚定链接”).offset().top);
-看起来像是一个额外的大括号?是的,它应该是scrollTop($(“#锚定链接”).offset().top)
。