当用户在我的页面上可滚动的特定 div 上拖动时,我试图调用一个函数。以下对我不起作用:
document.addEventListener("scroll", scroll, false);
$("#content").on("scroll", scroll, false);
$(document).on("scroll", scroll, false);
function scroll(){
alert("scrolled");
}
我试图捕捉滚动的 div 是#content
. 我认为上述其中之一会起作用,但它们不会产生任何错误,也不会被称为正确。
第一个根本不运行scroll
。第二个在用户滚动时调用该函数,而不是在最后。第三个只调用body
元素上的函数。
这是一个演示: http: //www.codekraken.com/snow/app_testing/test2.html
完整代码:
$(document).ready(function () {
var extra = $("#content").height() - $("#list").height();
if (extra > 0) {
$("#list").css("margin-bottom", extra);
}
$("#content").scrollTop("50");
var removeTransition = function () {
content.style['-webkit-transition-duration'] = 0;
};
content = document.getElementById('content');
pullToRefresh = document.getElementById('pull_to_refresh');
refreshing = document.getElementById('refreshing');
function success(callback) {
// simulate a network request that takes 2 seconds
window.setTimeout(function () {
var l = document.getElementById('list');
for (var i = 0; i < 5; i++) { // insert 5 new items
var li = document.createElement('li');
li.innerHTML = 'List Item ' + Math.floor(Math.random() * 100);
li.style.opacity = 0;
l.insertBefore(li, l.firstChild);
}
window.setTimeout(function () {
for (var i = 0; i < 5; i++) {
l.children[i].style.opacity = 1;
}
}, 0);
callback(); // pull callback when finished
}, 2000);
}
function start() {
console.log('start');
}
function cancel() {
console.log('cancel');
}
$("#content").on('scroll', function (e) {
var test = $("#list li").eq(1).offset().top - $("#list li").outerHeight();
if (test > 0) {
$("#content").scrollTop("50");
}
});
document.getElementById('content').addEventListener('touchend', function (e) {
if (refresh) {
content.style['-webkit-transition-duration'] = '.5s';
$("#content").scrollTop("0");
pullToRefresh.style.display = 'none';
refreshing.style.display = '';
success(function () { // pass down done callback
pullToRefresh.style.display = '';
refreshing.style.display = 'none';
$("#content").scrollTop("50");
content.addEventListener('transitionEnd', removeTransition);
});
refresh = false;
} else {
content.style['-webkit-transition-duration'] = '.25s';
$("#content").scrollTop("50");
content.addEventListener('transitionEnd', removeTransition);
cancel();
}
});
document.getElementById('content').addEventListener('touchmove', function (e) {
var test = $("#list li").eq(1).offset().top - $("#list li").outerHeight();
if (test === 0) {
refresh = true;
} else {
refresh = false;
}
});
document.getElementById('content').onscroll = function(){
alert("test");
};
});