如何使用JS跳转到页面中的特定位置?尝试scrollIntoView,无法正常工作

时间:2010-05-14 21:11:03

标签: javascript

我有一个用于讨论的PHP表单。每条消息都有自己的响应按钮,该按钮是动态生成的。我在按钮中使用javascript来在页面底部显示一个响应表单,但是我不能在我的生活中让页面一旦可见就跳转到表单。对于有很多讨论的网页来说,这是一个问题,因为有些用户可能不知道向下滚动,只会认为按钮不起作用。

以下是我现在的按钮代码:

<a href="#" onClick="changeVisibility(3,'responseForm')"><img src="images/reply.jpg" border=0 /></a>

changeVisibility函数如下所示:

function changeVisibility(parentID, elementID) {
  document.getElementById(elementID).style.visibility="visible";
  document.forms[0].parent_id.value=parentID;
  var el = document.getElementById(elementID);
  el.scrollIntoView(true);
}

在我的表单中,我有一个div,其id设置为responseForm。单击按钮时,div确实可见,但scrollIntoView不起作用 - 我必须手动向下滚动才能看到它。有什么想法吗?

5 个答案:

答案 0 :(得分:3)

使用window.location.hash

function changeVisibility(parentID, elementID) {
  document.getElementById(elementID).style.visibility="visible";
  document.forms[0].parent_id.value=parentID;
  window.location.hash = '#' + elementID;
  return false;
}

<a href="#" onClick="return changeVisibility(3,'responseForm')"><img src="images/reply.jpg" border=0 /></a> 
编辑:我认为之前的问题是你没有返回false,所以默认动作(转到#)仍在发生。

答案 1 :(得分:1)

用户window.location.hash重定向到ID /锚点。 E.g。

HTML:

<p id="youranchor">bla bla</p>

JavaScript的:

window.location.hash='youranchor';

艾美奖 - 此代码确实有效。以下是您的完整示例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
  <head>
    <title>Some title</title>

    <script type="text/javascript">
      function jumpToParagraph() {
        window.location.hash='paragraphjump';
      }
    </script>
  </head>
  <body>
    <p onclick='jumpToParagraph();'>Jump to the paragraph at the end! [version 1]</p>

    <p><a href="javascript:jumpToParagraph();">Jump to the paragraph at the end! [version 2]</a></p>

    <p style="height: 1500px;">Some nonsense</p>

    <p id="paragraphjump">You made the jump</p>
  </body>
</html>

将其放入文件并在浏览器中测试该文件。

答案 2 :(得分:0)

嗯,您可以尝试使用document.body.scrollTop = document.getElementById(elementId).offsetTop;(未经测试)

答案 3 :(得分:0)

嗯,以下JavaScript代码就像魅力一样:

<script type="text/javascript">
function scrollToPos() {
    var el = document.getElementById("abc");
    el.style.visibility = "visible";
    el.style.display = "block";
    el.scrollIntoView(true);
}
</script>

点击此链接<a href="#" onclick="scrollToPos();return false;">scroll</a><br /> 后,可以看到以下div获取并滚动到视图中(在IE6,IE8,FF3.6.3,Google Chrome 4.1和Opera 10.5中测试,全部在Windows上)

<div id="abc" style="height:100px;color:red;font-weight:bold;visibility:hidden;display:none;">
    abc
</div>

答案 4 :(得分:0)

好的,我终于找到了有用的东西。我一直在做我在石器时代所做的教训:当在需要的链接中使用javascript调用时,使用

a href="#" onClick="yourFunction()"

显然这是#为我杀了一些东西;如果我只是使用

a href="javascript:yourFunction()"

它正常工作。这可能会或可能不会被视为良好做法,但它确实有效。