水平滚动,通过AJAX加载内容

时间:2016-09-14 22:12:24

标签: javascript javascript-events

我有这个滚动事件,我想在滚动条到达结束之前通过ajax加载新内容。所以例如在滚动条到达结束之前40px我想加载新内容。

这有效,但它会多次加载内容。滚动期间会触发许多ajax请求。我想仅在滚动条接近结束时加载新内容,但我的函数在整个滚动事件期间加载内容。

//load with ajax
document.addEventListener('scroll', function(event) {

    var el = event.target;

    if((el.scrollWidth - el.scrollLeft) < (el.offsetWidth + 40)) {
        //get
    }
}, true);

1 个答案:

答案 0 :(得分:1)

这是jQuery中的一个快速小提琴 - 只是为了说明使用.getBoundingClientRect().left;跟踪最后一个div,如果你不想这样做,那么它会说明阻止条件语句的loading变量在这是真的时再次开火。

var n = 0, loading = false, lastDiv;

function addboxes(){
  for( i=0; i < 6; i++){
   $('body').append('<div class="box" style="left:'+(n+i*250)+'px;"></div>');
  }
	n+=6*250;
  loading = false;
}

addboxes();
// just to set up sideways boxes

$(document).on('scroll',function(e){
	var lastDiv = $('.box').last();	// get the last div
	var lastLeft = lastDiv[0].getBoundingClientRect().left; // get distance between lastDiv's left edge and windows left edge
  var windowWidth = $(window).width(); // get window width
  
	$("#monitor").text(" lastLeft ="+lastLeft+", windowWidth ="+windowWidth);

	if( lastLeft < windowWidth && !loading ){	// last box is now just appearing!
  	loading = true; // flag to prevent multiple firings
		addboxes(); // add more boxes!
    $(window).trigger('resize');	// just incase window doesn't recalc for new content, probably not necessary
  }

});
.box {
  position: absolute;
  width: 200px;
  height: 100px;
  background: #333;
}

#monitor{
  position: fixed;
  left: 20px;
  bottom: 30px;
  color: #09f;
  z-index: 333;
}
<script   src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>

<div id="monitor">
</div>

相关问题