我有一个固定高度为 400 像素的 div,里面有一长串项目。单击上一个/下一个链接将使您浏览列表。问题是,过一会儿,当前项目就会消失。如何移动当前项目的滚动条?
我做了个demo,看看:http://jsbin.com/idunaf
<!DOCTYPE html>
<html>
<head>
<style>
#listContainer{height:400px;width:300px;overflow:auto;background-color:#eee;}
.selectedItem{background-color:white;color:red;}
</style>
<script class="jsbin" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
for(var a=[],i=0;i<100;++i){
a[i]=i;
}
currentItem = 0;
$(document).ready(function() {
var items = [];
$.each(a, function(i,x){
items.push('<li id="item_'+x+'">item #'+x+'</li>');
});
$('#list').append(items.join(''));
$('#next').click(function() { updateList(); currentItem += 1; });
$('#prev').click(function() { updateList(); currentItem -= 1; });
});
function updateList(){
$('#listContainer').find('.selectedItem').removeClass('selectedItem');
$('#item_'+currentItem).addClass('selectedItem');
}
</script>
</head>
<body>
<a href="javascript:void(0)" id="prev"><< PREV ITEM</a> | <a href="javascript:void(0)" id="next">NEXT ITEM >></a>
<div id="listContainer">
<ul id="list"></ul>
</div>
</body>
</html>
最佳答案
您应该能够使用(非 jQuery)DOM 方法 element.scrollIntoView()
:
$('#item_'+currentItem).addClass('selectedItem')[0].scrollIntoView(true);
// or
$('#item_'+currentItem)[0].scrollIntoView(true);
// or
document.getElementById('item_'+currentItem).scrollIntoView(true);
[0]
只是为了从 jQuery 对象中获取对实际 DOM 元素的引用——假设您是通过 id 选择的,我假设只能有一个元素与选择器匹配。当然,大多数 jQuery 方法设置为允许链接,您可以在现有 .addClass()
的末尾执行此操作,而不是再次选择元素。
(查看 .scrollIntoView()
doco 来决定是将 true 还是 false(或什么都不传递)传递给该方法。)
关于javascript - 如何在溢出的 div 中保持当前项目可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8380581/