簡體   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