繁体   English   中英

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

[英]How to use JS to jump to a specific place in a page? Tried scrollIntoView, not working

我有一个用于讨论的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不起作用 - 我必须手动向下滚动才能看到它。 有任何想法吗?

使用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,所以默认动作(转到#)仍在发生。

用户window.location.hash重定向到ID /锚点。 例如

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>

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

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

嗯,以下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 get可见并滚动到视图中(在IE6,IE8,FF3中测试) .6.3,谷歌Chrome 4.1和Opera 10.5,全部在Windows上)

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

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

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

显然,这对我来说是在扼杀事物的#。 如果我只是用

a href="javascript:yourFunction()"

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM