简体   繁体   English

检查某个部分的页面

[英]check if page at a certain section

I want to trigger a function when the user is on a section of the page with a specific ID (either through a link or scroll). 我想在用户位于具有特定ID(通过链接或滚动)的页面的一部分时触发功能。 This is what I have now but it's not working. 这就是我现在所拥有的,但它不起作用。

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

UPDATE: Found what I was looking for. 更新:找到我要找的东西。 This is what I used: 这是我用过的:

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

The "- 50" is to account for my margins and paddings. “ - 50”用于说明我的边距和填充。 When using the subtract symbol it 'assumes' your section starts higher on your page. 使用减法符号时,它“假设”您的部分在页面上开始更高。 For lower, use addition. 对于较低的,使用添加。
The "$('.modal').modal('hide');" “$('。modal')。modal('hide');” is not needed. 不需要。 This is to hide a bootstrap modal when the user is on the #contact section of the page. 这是为了在用户位于页面的#contact部分时隐藏引导模式。

The window.location property in Javascript returns a location object . Javascript中的window.location属性返回一个位置对象 If you want to match a specific anchor link you need to use the hash property of the location object. 如果要匹配特定的锚链接,则需要使用位置对象的hash属性。 Here's a list of all properties of location objects: http://www.w3schools.com/jsref/obj_location.asp . 以下是位置对象的所有属性列表: http//www.w3schools.com/jsref/obj_location.asp

You could check for window.location.pathname+window.location.hash 您可以检查window.location.pathname+window.location.hash

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

because window.location.pathname does not include the part after the hash. 因为window.location.pathname不包含散列后的部分。

Your Html code 你的Html代码

<div id="contact">

</div>

Your Javascript code 您的Javascript代码

 $("#contact").scroll(function() {
/*do whatever you want*/
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM