判斷元素在滾動區域是否可見,不可見時滾動到可見區域。
var itemHeight = $('.item').height(); // 元素高度 var wrapHeight = $('.wrap').height(); // 滾動區域容器高度 var index = $('.item').index($('.item')); // 當前元素序號 var itemHeightTop = itemHeight * index; // 當前元素距離容器頂部高度 var curScrollTop = $('.wrap').scrollTop(); // 當前滾動條滾動距離 if (itemHeightTop < curScrollTop || curScrollTop < itemHeightTop - wrapHeight) { // document.documentElement.scrollTop = itemHeightTop // 滾動容器是body時有效
$('.wrap').scrollTop(itemHeightTop);
}