我正在尝试在用户滚动时移动元素。
如果可能的话,向上滚动一个班级,然后向下滚动。
我希望元素只有在某个条件成立时才与滚动一起移动。
因此,如果hasScrolledUp
和scrollingUp
都为真,我希望元素在用户向上滚动时向下移动。
然后,如果downAfterUp
为真,我希望元素在用户向下滚动时向上移动。
以下是我设置的布尔代码:
var lScrollTop = 0;
var hasScrolledUp = false;
var scrollingUp = false;
var downAfterUp = false;
$(window).scroll(function(){
var scrollTop = $(this).scrollTop();
if(scrollTop>lScrollTop){
hasScrolledUp = true;
scrollingUp = true;
}
else{
if(scrollingUp) scrollingUp = false;
if(hasScrolledUp) downAfterUp = true;
}
lScrollTop = scrollTop;
});
我非常感谢任何帮助!
答案 0 :(得分:1)
我建议您查看此示例: stackoverflow.com/a/24815216...
scroll event 在Firefox中表现得很奇怪,由于平滑滚动,它被解雇了很多次,但它有效,这里有一个例子:
//creates an element to print the scroll position
$("<p id='test'>").appendTo("body").css({
padding: "5px 7px",
background: "#e9e9e9",
position: "fixed",
bottom: "35px",
left: "35px" });
//binds the "scroll" event
$(window).scroll(function (e) {
var target = e.currentTarget,
scrollTop = target.scrollTop || window.pageYOffset,
scrollHeight = target.scrollHeight || document.body.scrollHeight,
lastScrollTop = $(target).data("lastScrollTop") || 0,
scrollText = "";
if (scrollTop > lastScrollTop) {
scrollText = "<b>scroll down</b>";
} else {
scrollText = "<b>scroll up</b>";
}
$("#test").html(scrollText +
"<br>scrollTop: " + scrollTop +
"<br>lastScrollTop: " + lastScrollTop);
if (scrollHeight - scrollTop === $(target).innerHeight()) {
console.log("► End of scroll");
}
//saves the current scrollTop
$(target).data("lastScrollTop", scrollTop);
});
答案 1 :(得分:1)
添加到 jherax 的答案,我添加了一个移动位置的函数:固定div在每个滚动条上的百分比。
function ScrollMoveDiv(scrollTop){
var windowHeight = $(window).height();
var totalHeight = $(document).height() - windowHeight;
var MovePercentage = (scrollTop * 100)/totalHeight;
return MovePercentage+"%";
}
//attaches the "scroll" event
$(window).scroll(function (e) {
var body = document.body,
scrollTop = $("html").scrollTop() || $(body).scrollTop(),
lastScrollTop = $(this).data("lastScrollTop") || 0,
scrollText = "";
if (scrollTop > lastScrollTop) {
scrollText = "<b>scroll down</b>";
} else {
scrollText = "<b>scroll up</b>";
}
var MoveDistance = ScrollMoveDiv(scrollTop);
$('.moving').css('bottom',MoveDistance);
$("#test").html(scrollText +
"<br>lastScrollTop: " + lastScrollTop +
"<br>currentScrollTop: " + scrollTop);
//saves the current scrollTop
$(this).data("lastScrollTop", scrollTop);
});
JSFiddle:http://jsfiddle.net/8MJnB/