【问题标题】:Link to another page, execute function, then jump to anchor链接到另一个页面,执行函数,然后跳转到锚点
【发布时间】:2015-11-12 06:44:33
【问题描述】:

我有两页。第一个有一个slideshow,它允许我为每张幻灯片添加链接。第二页有许多展开的 div,可以使用这个显示/隐藏功能展开/折叠 onclick:

 function showtxt(divID) {
   var item = document.getElementById(divID);
   if (item) {
     item.className=(item.className=='hidetxt')?'showtxt':'hidetxt';
   }
 }

然后该页面上的每个展开/折叠 div 都有自己的函数在点击时调用它:

function ANCHORbutton() { 
  var img = document.getElementById('expANCHORbutton').src;
  if (img.indexOf('plus.png')!=-1) { 
    document.getElementById('expANCHORbutton').src  = 'minus.png'; 
  }
  else { 
    document.getElementById('expANCHORbutton').src = 'plus.png'; 
  } 
}

如果可能的话,我想做的是将幻灯片中的每张幻灯片链接到第二页,展开相应的 div,然后将页面向下跳转到指定的锚点。

如果我没有将所有内容都折叠起来,那将是一个简单的href="http://domain.com/page2.html#ANCHOR",但我正在努力解决如何在跳到我的锚点之前扩展适当的部分。

【问题讨论】:

  • 欢迎来到 SO。如果您访问help center,您可以看到我们希望看到一些正在运行的代码。当然,一些 HTML 会很有用。
  • 您仍然可以使用 page2.html#ANCHOR - 在您的代码中添加对 location.hash 的测试以查看要扩展的 div。例如if (location.hash) showtxt(location.hash.substring(1))
  • 谢谢,@mplungjan。因此,我将链接到第二页并正常锚定,然后 location.hash 将在主题标签之后收集指定的锚点,然后我必须运行我的函数并展开与使用 location.hash 收集的值相关联的指定 div最后运行另一个函数来跳转到那个id?我将不得不在明天晚上回来完成添加我所有的代码。
  • 假设 ID 是唯一的,#divId 应该会自动跳转到 ID。然后该功能可以扩展它。无需编程跳转
  • 问题是所有的div都折叠了,页面上的所有东西都可以看到(没有滚动),所以除非div已经展开,否则它不会跳转到它。

标签: javascript hyperlink anchor


【解决方案1】:

问题 1:折叠的 div 全部显示,因此无需浏览器滚动
问题 2:隐藏的 div 没有被滚动到,因为它们被隐藏了。

解决方案可能是页面底部的这个(在某些浏览器上重新加载时不会触发 onload)

<script>
var hash = location.hash;
if (hash) {
  var divID = hash.substring(1); // remove the #
  showtxt(divID);
  document.getElementById(divID).scrollIntoView();
}
</script>
</body>

更新添加100px:

var hash = location.hash;
if (hash) {
  var divID = hash.substring(1); // remove the #
  showtxt(divID);
  var div = document.getElementById(divID); 
  div.scrollIntoView(); 
  div.style.top=(parseInt(div.style.top,10)+100)+"px"; 
}

【讨论】:

  • 你完美地解决了我的问题——谢谢!但是,我没有意识到我的固定标题/导航覆盖了标题标签和 div 的第一部分。脚本将锚点滚动到页面顶部,但页面的前 ≈100px 被固定页眉覆盖。有没有办法可以修改 .scrollIntoView() 以从页面顶部偏移 100 像素?
  • 你可以试试var div = document.getElementById(divID); div.scrollIntoView(); div.style.top=(parseInt(div.style.top,10)+100)+"px";
  • 除非我做错了什么,否则没有用:&lt;script&gt; var hash = location.hash; if (hash) { var divID = hash.substring(1); showtxt(divID); document.getElementById(divID); div.scrollIntoView(); div.style.top=(parseInt(div.style.top,10)+100)+"px"; } &lt;/script&gt;
  • 你做了,showtxt(divID); document.getElementById(divID); 应该是 showtxt(divID); var div = document.getElementById(divID); - 查看更新
  • 这是我现在正在使用的,但仍然无法正常工作:&lt;script&gt; var hash = location.hash; if (hash) { var divID = hash.substring(1); showtxt(divID); var div = document.getElementById(divID); div.scrollIntoView(); div.style.top=(parseInt(div.style.top,10)+100)+"px"; } &lt;/script&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-05
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多