我想在用户位于具有特定 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 部分时隐藏引导模式。
最佳答案
Javascript 中的 window.location
属性返回一个 location 对象。如果你想匹配一个特定的 anchor 链接,你需要使用位置对象的 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
不包含 hash 之后的部分。
关于javascript - 检查页面是否在某个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30153580/