我有一些带有链接的页脚:
<a href="javascript:void(0)" onClick="goToByScroll('newServices')">
Our Services
</a>
如果用户在主页中,则第一个IF工作正常,但如果用户不在主页中,则会重定向到主页,但不会在特定div中打开。
function goToByScroll(id){
if ( window.location.href.indexOf('newhome') > -1 ) {
$('html,body').animate({scrollTop: $("#"+id).offset().top},1000);
}
else {
window.location = "/newhome/"
$('html,body').animate({scrollTop: $("#"+id).offset().top},1000);
}
}
有什么想法吗?
*********** UPDATE *********************
var userClickID = id;
if ( window.location.href.indexOf('newhome') > -1 ) {
$('html,body').animate({scrollTop: $("#"+userClickID).offset().top},1000);
}
else {
window.location = "/newhome/";
$(document).ready(function() {
$('html,body').animate({scrollTop: $("#"+userClickID).offset().top},1000);
});
}
仍然无法正常工作。
答案 0 :(得分:0)
实际上我正在桌面上的本地.html文件上进行这些实验:
file:///C:/Users/myusername/Desktop/page2.html
此示例使用?
url参数滚动到您的div:
<a href="page2.html?newServices">page2 - newServices</a>
因此,使用以下代码在桌面上创建两个.html页面:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var href = window.location.href;
var split = href.split("?");
var afterSplit = "Error parsing url";
if (split[1] != null) {
afterSplit = split[1];
}
console.log(afterSplit);
goToByScroll(afterSplit);
});
</script>
<style type="text/css">
.myDiv {width: 200px;height: 2000px;}
#one {border: 3px solid green;}
#two {border: 3px solid blue;}
#three {border: 3px solid red;}
</style>
</head>
<body>
<div id="one" class="myDiv">ONE<button onclick="goToByScroll('two');">goToByScroll</button><a href="page2.html?three">page2.html?three</a></div>
<div id="two" class="myDiv">TWO<button onclick="goToByScroll('three');">goToByScroll</button></div>
<div id="three" class="myDiv">THREE<button onclick="goToByScroll('one');">goToByScroll</button></div>
<script type="text/javascript">
var timeMs = 1000;
function goToByScroll(ID){
$('body').animate({scrollTop: $('#'+ID).offset().top}, timeMs);
}
</script>
</body>
</html>
告诉我这是否是你想要的
希望有所帮助