我有一种情况,我希望在<div>
内滚动时更新变量。根据此变量更新,还会发生一系列其他事情,因此我不想将其包含在scroll事件中。有没有办法避免这种情况?
这是我的JS:
var scrollEl = document.getElementById("scrollEl");
var scrollElWidth = scrollEl.offsetWidth;
var scrolled = 0;
var updater = function(updated) {
scrolled = Math.round(updated);
return scrolled;
}
scrollEl.addEventListener("scroll", function() {
var percentage = 100 * scrollEl.scrollLeft / (scrollEl.scrollWidth - scrollElWidth);
//This works
console.log(updater(percentage));
});
//This doesn't
console.log('Updated scroll variable: ', scrolled);
这是一个小提琴:https://jsfiddle.net/0u4fp0yv/