我只是想知道当使用窗口滚动功能到某个id而不是像素高度时是否可以触发警报。我问的原因是我意识到高度会因显示的位置而有所不同,因此引用id可能会更有效率。
答案 0 :(得分:3)
使用 .position() .offset(),您可以获得元素的位置。
将它与您的滚动功能相结合,您将有一个“窗口滚动功能到id”。
// store the position of the element in position
var position = $('#idOfElement').offset(); //=position() but always relative to
//document instead of parent.
//thanks to sidonaldson
// on scrolling of the document do something
$(document).scroll(function () {
//the current height
var y = $(this).scrollTop();
//If the current Y is bigger than the element. (you scrolled beyond the element)
if(y >= position.top){
//do something
}else{
//do something else
}
});
答案 1 :(得分:3)
使用jQuery,您可以将页面设置为id。
$("html, body").animate({ scrollTop: $('#your-id').offset().top }, 1000, function(){
alert("Scroll end");
});
首先,您必须使用'html,body'使其跨浏览器。
然后你通过计算它相对于页面顶部的偏移量来计算id元素的位置(而不是相对于父元素的位置)
然后用ms设置你的速度。
最后传入一个函数引用,或者在这种情况下,定义一个回调函数 - 在这里你可以添加你的警报。
请注意,这必须在document.ready被解雇之后。
答案 2 :(得分:2)
试试这个:
//getting the Y position of the element you want to scroll to
var position = $('#element').offset().top;
//scrolling to the element with an animation of 700 miliseconds
$('body').animate({
scrollTop: position
}, 700, function(){ //callback function (executed when animation finishes)
alert("Hello there!");
});