如何在视口中获取选定的div?

时间:2018-08-13 13:39:45

标签: javascript scroll

$('.lorem').click(function() {
  $('.active').removeClass('active');
  $(this).addClass('active');
});

$(document).keydown(function(e){
    e.preventDefault();
		var i = $('.active').index('.lorem') + 1;
		var next = $('.lorem').eq(i);
		$('.active').removeClass('active');
		next.addClass('active');
});
.lorem{
line-height:21px;
cursor:pointer;
}

.active{
background:gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>

我具有上面的代码,可以通过按lorem箭头键来选择下一个课程down

和类似的代码,通过按lorem箭头键来选择上一个up

想象一下,页面上还有lorem个div(大约200个)。

当选定的div在视口之外时,是否有一种自动滚动页面的方法,因此它会在视口内?

1 个答案:

答案 0 :(得分:0)

您可以将此代码添加到按键监听器中:

$('html, body').animate({
     scrollTop: next.offset().top
}, 1000);

并检查视口中是否有元素:

function isElementInViewport(el) {
     var rect = el.getBoundingClientRect();
     return (
           rect.top >= 0 &&
           rect.left >= 0 &&
           rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
           rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
     );
}

它将向下滚动页面到下一个元素。

function isElementInViewport(el) {
 var rect = el.getBoundingClientRect();
 return (
   rect.top >= 0 &&
   rect.left >= 0 &&
   rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
   rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
   );
}

$('.lorem').click(function() {
  $('.active').removeClass('active');
  $(this).addClass('active');
});

$(document).keydown(function(e){
    e.preventDefault();
	var i = $('.active').index('.lorem') + 1;
	var next = $('.lorem').eq(i);
	$('.active').removeClass('active');
	next.addClass('active');

    if (next[0] && !isElementInViewport(next[0])) {
        $('html, body').animate({
            scrollTop: next.offset().top
        }, 1000);
    } 
});
.lorem{
line-height:21px;
cursor:pointer;
}

.active{
background:gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>
<div class='lorem'>lorem</div>