使用URL参数来滚动到div(模拟锚点行为)

3
我正在使用一个jQuery选项卡插件,它使用锚点来定义默认打开的选项卡。但是,如果界面在屏幕下方,它不会滚动到视图中。我尝试在界面上方添加锚点标记,但我无法使其突出显示适当的选项卡并滚动到视图中。由于我不能使用两个锚点,我的想法是如果我想提供一个链接来滚动到视图中,我可以在URL中包含一个参数,例如: http://stage.ravencreative.com/scroll/Index.html?scrollto=Interface#parentHorizontalTab2 (其中“Interface”可能是界面顶部的锚点或ID名称) 我在谷歌和stackoverflow上搜索了一下,但找不到任何东西。是否有某种脚本可以让这个工作?或者有更好的方法吗? 这里有一个可用的示例: http://stage.ravencreative.com/scroll/Index.html 这会使第二个选项卡处于活动状态: http://stage.ravencreative.com/scroll/Index.html#parentHorizontalTab2 (#parentHorizontalTab2 是默认打开第二个选项卡的原因)
这会滚动到选项卡界面: http://stage.ravencreative.com/scroll/Index.html#Interface (#Interface 是界面开头的锚点)
但是我无法同时让两者起作用。 有什么建议吗? 是否有一种方式可以执行以下操作: http://stage.ravencreative.com/scroll/Index.html?scrollto=Interface#parentHorizontalTab2其中脚本会检测 scrollto 参数并将其滚动到该位置?
类似于(我使用英语,因为我不熟悉代码结构):
if scrollto is found in the URL
then scroll to the anchor defined in the scrollto

请至少附上一些代码或几张截图。 - Jason Sears
谢谢你的建议,我用实时演示示例重写了问题。 - Rothgarr
你能不能使用一点JavaScript来选取目标选项卡并点击它呢?例如:jQuery("#parentHorizontalTab ul li")[1].click(); - adammtlx
抱歉,我不确定这是什么意思。有时我只需要选中某个选项卡,而不需要像这些链接一样滚动到选项卡界面:http://stage.ravencreative.com/scroll/Index.html#parentHorizontalTab2 或 http://stage.ravencreative.com/scroll/Index.html#parentHorizontalTab3。但有时我可能需要让URL自动滚动到该接口。这就是为什么我认为可以通过在URL中包含参数"?scrollto=Interface"来实现。 - Rothgarr
2个回答

3
你可以像你描述的那样使用各种#tabConditionSelector条件,然后在document.ready中读取它,并根据不同情况进行滚动/选择和其他操作。
使用jQuery:
$( window ).load(function() {

    var hash = window.location.hash;

    if (hash == "#parentHorizontalTab2") {
      var top = document.getElementById("Interface").offsetTop; //Getting Y of target element
      window.scrollTo(0, top);

    } else if (hash == "#parentHorizontalTab3") {
      //select tab 3 etc
    }
});

2
此外,我建议在$(window).load上使用scrolling method而不是$(function(){(又称$(document).ready)。这样,您可以确保在尝试滚动之前,所有内容都已完全加载并创建了页面长度。 - SpYk3HH
当我更新使用location.hash时,忘记了必须包含井号,例如:==“#parentHoriaontalTab2” - Steve Seeger
请查看我的最后一条评论。 - Steve Seeger
我意识到 .scrollTo() 不是内置于 jQuery 中的,抱歉!那个编辑只适用于 jQuery。 - Steve Seeger
没问题!我尝试了更新的代码,但在这里滚动无效:http://stage.ravencreative.com/scroll/Index.html#parentHorizontalTab2 - Rothgarr
显示剩余4条评论

1
你可以使用这个功能从链接哈希值加载时滚动到特定位置。
    $(window).load(function () {

        var hash = window.location.hash;

        $('html, body').animate({
            scrollTop: $(hash).offset().top
        }, 'slow');

    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接