在页面加载时,如果URL散列与数组中的某个值匹配,请滚动到具有匹配的data-load-id属性的元素 [英] On page load, if URL hash matches one of the values in the array, scroll to the element with the matching data-load-id attribute

查看:80
本文介绍了在页面加载时,如果URL散列与数组中的某个值匹配,请滚动到具有匹配的data-load-id属性的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有以下内容:

var scrollingAnchorIds = [];
    var getTheseIds = $(".anchor-content").each(function() {
        scrollingAnchorIds.push($(this).data('load-id'));
    });
    console.log(scrollingAnchorIds);

    $(window).bind("load", function() {
        if(document.URL.indexOf(scrollingAnchorIds[i]) >= 0){ 
            $('html,body').animate({scrollTop: elementWithMatchingDataLoadIdGoesHere.offset().top - 50},850);
        }
    });

我得到每个data-load-id的值,将它们添加到数组中。现在我坚持检查页面何时加载,url是否包含该哈希值,如果是,则滚动到具有匹配值的元素。

I get the values of each data-load-id, add them to array. Right now I'm stuck on checking when the pages loads, does the url contain that hash value, if so, scroll to the element with the matching value.

示例html它将滚动到哪个元素:

sample html of what element it would scroll to:

<div data-load-id="#83" class="anchor-content"></div>
<div data-load-id="#91" class="anchor-content"></div>
<div data-load-id="#99" class="anchor-content"></div>


推荐答案

在考虑它时,你的大部分代码似乎都过多了。尝试这样的事情:

When thinking about it, most of your code seems excessive. Try something like this:

$(function(){
    $('html,body').animate({scrollTop: $("[data-load-id='" + window.location.hash + "']").offset().top - 50},850);
});

我做了一个小提琴,虽然window.location.hash在这方面不起作用。

I made a fiddle also, though window.location.hash does not work in this.

这篇关于在页面加载时,如果URL散列与数组中的某个值匹配,请滚动到具有匹配的data-load-id属性的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆