【问题标题】:Capturing back navigation within page捕获页面内的返回导航
【发布时间】:2014-07-03 17:55:46
【问题描述】:

正如您从下面的代码中看到的那样,我正在使用 a 标签在网页上的标题之间导航。当导航发生时,我需要调整一些 div 的大小,我正在使用一个 JS 函数来执行此操作,该函数的工作方式与单击按钮时应有的方式相同。

然而当用户按下浏览器的后退或前进 按钮时,不会调用 javascript 函数并且不会调整 div 的大小,这会使我的页面大打折扣。

有人对如何解决此问题有建议吗?

<a href="#header1" onclick="resizeContainer(this)">Go to header 1</a>
<a href="#header2" onclick="resizeContainer(this)">Go to header 2</a>

【问题讨论】:

标签: javascript html


【解决方案1】:

在我看来,如果你采取不同的方式,你可以拥有更多的控制权。我为您创建了一个工作示例,您可以在这里找到并编辑它http://jsbin.com/jociy/5/

否则,请关注:

$(document).ready(function(){

 $('.bar').on('click', function(){

    var hash = $(this).attr("href");

    // get the element position
    var toPosition = $(".foo[hash='" + hash + "']").offset().top;

    // scroll to the element position
    $('html, body').animate({
      scrollTop: toPosition
    }, "slow", function(){

      console.log("Expand fn() goes here!");

    });

 });

});

了解发生了什么的 HTML:

  <a href="#foo1" class="go bar">Foo 1</a>
  <br>
  <a href="#foo2" class="go bar">Foo 2</a>

  <div class="foo red">I'm red!</div>
  <div class="foo green" hash="#foo1">I'm green!</div>
  <div class="foo blue">I'm blue!</div>
  <div class="foo yellow" hash="#foo2">I'm yellow!</div>

就是这样!希望对您有所帮助!

【讨论】:

  • @Fester 如果您需要查看“扩展 fn()”示例,我可以向您展示,但我认为这是基本的。在我看来,我的解决方案非常容易阅读、轻便(不需要插件等),并且不会阻止哈希值显示在 url 中。等
【解决方案2】:

我会查看 Ben Alman 的 jQuery BBQ 插件,位于:http://benalman.com/projects/jquery-bbq-plugin/

它允许您在哈希更改时进行回调。

【讨论】:

  • 我最终只使用了onhashchange 事件,但我在您链接的网站上找到了它。
【解决方案3】:
window.onbeforeunload = function (e) {
  var message = "Your message goes here.",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }

  // For Safari
  return message;
};

阅读Mastering The Back Button With Javascript

【讨论】:

  • 我尝试了 unbeforeunload 事件,但是由于页面没有重新加载它不会被调用所以不能解决我的问题。
猜你喜欢
  • 2022-09-24
  • 1970-01-01
  • 2012-08-12
  • 1970-01-01
  • 2020-02-10
  • 2019-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多