锚点URL的替代方案

时间:2015-02-21 12:05:40

标签: javascript html url anchor

是否有其他方法可以链接到同一页面上的元素而不使用锚点网址?

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Alternative to anchor URL</title>
</head>

<body>

<input type="button" value="Go there &raquo;" />

<div style="height:1280px;"></div>

<div id="goHere" style="width:360px;height:240px;background-color:#61b2cc"></div>

</body>
</html>

2 个答案:

答案 0 :(得分:8)

有!请看下面的代码:

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Alternative to anchor URL</title>

<script type="text/javascript">
function scrollWindow() {
  {
  var top = document.getElementById('goHere').offsetTop;
  window.scrollTo(0, top);
  }
}
scrollWindow();
</script>
</head>

<body>

<input type="button" onclick="scrollWindow()" value="Go there &raquo;" />

<div style="height:1280px;"></div>

<div id="goHere" style="width:360px;height:240px;background-color:#61b2cc"></div>

</body>
</html>

答案 1 :(得分:2)

使用jQuery:

$("button").click(function(){
    window.scrollTo($("#goHere").offset().top);
});