检查某个部分的页面

时间:2015-05-10 16:09:32

标签: javascript jquery

我想在用户位于页面上具有特定ID(通过链接或滚动)的部分时触发功能。这就是我现在所拥有的,但它不起作用。

$(document).ready(function() {
    if (window.location.pathname == '/index.html#contact') {
        console.log('Viewing contact form');
    }
});

更新:找到我要找的东西。这是我用过的:

$(window).bind('scroll', function() {
    if($(window).scrollTop() >= $('#contact').offset().top - 50) {
        $('.modal').modal('hide');
    }
});

“ - 50”是我的边距和填充。使用减法符号时,它“假设”您的部分在页面上开始更高。对于较低的,使用添加。
“$('。modal')。modal('hide');”不需要。这是为了在用户位于页面的#contact部分时隐藏引导模式。

1 个答案:

答案 0 :(得分:3)

Javascript中的window.location属性返回位置对象。如果要匹配特定的锚链接,则需要使用位置对象的hash属性。这是位置对象的所有属性的列表:http://www.w3schools.com/jsref/obj_location.asp

您可以查看window.location.pathname+window.location.hash

$(document).ready(function() {
    if (window.location.pathname+window.location.hash == '/index.html#contact') {
        console.log('Viewing contact form');
    }
});

因为window.location.pathname不包括散列后的部分。