【发布时间】:2013-09-24 06:56:50
【问题描述】:
我只是想知道在使用窗口滚动功能到某个 id 而不是以像素为单位的高度时是否可以触发警报。我问的原因是我意识到高度会根据显示位置而有所不同,因此引用 id 可能更有效。
【问题讨论】:
标签: jquery
我只是想知道在使用窗口滚动功能到某个 id 而不是以像素为单位的高度时是否可以触发警报。我问的原因是我意识到高度会根据显示位置而有所不同,因此引用 id 可能更有效。
【问题讨论】:
标签: jquery
使用 .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
}
});
【讨论】:
使用 jQuery,您可以将页面动画化为 id。
$("html, body").animate({ scrollTop: $('#your-id').offset().top }, 1000, function(){
alert("Scroll end");
});
首先你必须使用 'html,body' 让它跨浏览器。
然后你通过计算它相对于页面顶部的偏移量来计算 id 元素的位置(而不是相对于父元素的位置)
然后你以毫秒为单位设置你的速度。
最后你传入一个函数引用,或者,在这种情况下,定义一个回调函数 - 在这里你可以添加你的警报。
请注意,这必须在 document.ready 被触发之后。
【讨论】:
html,body。只需body,它就适用于我测试过的所有浏览器。 (IE9、Chrome、Opera 12、Firefox...)哪些没有?
试试这个:
//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!");
});
【讨论】:
el.top;但想在他到达el.top 时触发一些东西。至少这是我对他的问题的看法。