【问题标题】:OnClick loads new HTML doc and should scroll to the bottom of itOnClick 加载新的 HTML 文档并且应该滚动到它的底部
【发布时间】:2015-01-08 13:06:45
【问题描述】:

我正在制作一个简单的交互式原型,其中包含不同的 HTML 文档,其中包含图像和可点击的 div,以模仿原型中按钮的行为。现在我想创建单击页面顶部的链接的行为,该链接应将用户滚动到页面底部并显示图像的特定部分(该行为几乎模仿了远程扩展并在手风琴控制)。

现在我已经搜索了自动滚动到标记的某个部分的 JS 解决方案,问题是我似乎无法找到一个示例来说明如何在加载新的 HTML 文档时执行此操作。

我不确定加载新的 HTML 是否会使事情变得复杂,但我缺乏网络开发经验,这对我来说似乎非常困难。

这几乎是我现在的方法,但不起作用:

HTML 文档 1

<div #akebutton style="position:relative;
    top:-1137px;
    left:410px;
    width:33px;
    height:20px;
    border:1px solid #000;">
        <a href="02_ake expanded.html">
            <span style="position:absolute;width:100%;height:100%;top:0;left: 0;z-index: 1;">
            </span>
        </a>

    </div>

Javascript

$("#akebutton").click(function() {
    $('html, body').animate({
        scrollTop: $("#bottomDiv").offset().top
    }, 2000);
});

HTML 文档 2

<body>
    <img src="ake expanded.png" align="middle">
    <div style="position:relative;top:-502px;left:167px;width:1069px;height:47px;border:0px solid #000;">
        <a href="01_start.html">
            <span style="position:absolute;width:100%;height:100%;top:0;left: 0;z-index: 1;">
            </span>
        </a>

    </div>

    <div id="bottomDiv"></div>

    <script type="text/javascript" src="maintainscroll.jquery.min.js"></script> 

</body>

【问题讨论】:

  • &lt;div #akebutton 在 html 文档 1 中应该是 &lt;div id="akebutton"。
  • @Jai 谢谢!这对我来说是一个令人尴尬的错误。不幸的是,这并没有使它起作用,但是您从未说过它会起作用。 :)
  • html anchor 是解决方案吗?
  • @RaraituL 锚点只能在同一个 HTML 文档中使用吗?没有?
  • @AndroidHustle 嗯,不。例如,检查这个link with an anchor 你会看到它自动滚动到你的评论:)

标签: javascript jquery html autoscroll


【解决方案1】:

问题可能是这样的:

<div #akebutton style="position:relative;

你必须在哪里输入一个有效的 id:

<div id="akebutton" style="position:relative;

在js中你应该使用event.preventDefault()来防止默认行为:

$("#akebutton").click(function(e) {
   e.preventDefault(); // it would stop the jump of the anchor.
   $('html, body').animate({
      scrollTop: $("#bottomDiv").offset().top
   }, 2000);
});

注意:

akebutton 和 bottomDiv 应该根据您编写的 js 代码在同一页面上。


在我看来你想滚动到加载的页面,如果是这种情况,那么在准备好的文档中你可以这样做:

$(function(){
     var hash = location.hash;
     if(hash.length){
        $('html, body').animate({
              scrollTop: $(hash).offset().top
        }, 2000);
     }
});

在您的标记中,您的锚点应该以这种方式传递哈希:

<a href="02_ake expanded.html#bottomDiv">

【讨论】:

  • 谢谢!我会执行你的更改。然而,JS 位于一个单独的文档中,该文档被导入。
  • 这确实使滚动工作,另一方面,它似乎也覆盖了新 HTML 文档的加载,因此它滚动到 HTML 1 文档而不是 HTML 2 文档的底部。 ..
  • 我猜是 JS 点击事件捕获了点击而不是我在 HTML 中的链接元素(它加载了另一个 HTML 文档)?
  • 啊,链接的 div ID 扩展非常适合我的解决方案,缺少滚动动画并没有真正困扰我,因为它是概念证明而不是产品。但是,如果我选择在点击时使用 JS 动画,那么您认为可以使用您在答案中添加的最后一段 JS 来完成?
猜你喜欢
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 2011-01-12
  • 2010-12-18
  • 1970-01-01
相关资源
最近更新 更多