如何使用 JavaScript 或 jQuery 滚动选择列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7205702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to scroll a select list with JavaScript or jQuery?
提问by Zemzela
I have a select tag:
我有一个选择标签:
<select size="3">
<option value="1">value 1</option>
<option value="2">value 2</option>
<option value="3">value 3</option>
<option value="4">value 4</option>
<option value="5">value 5</option>
<option value="6">value 6</option>
<select>
Now it displays first 3 options, how can I scroll to see elements from 3-5 or 4-6 using jQuery or pure JavaScript?
现在它显示前 3 个选项,如何使用 jQuery 或纯 JavaScript 滚动以查看 3-5 或 4-6 中的元素?
回答by Arnaud Le Blanc
.scrollTop()
may work:
.scrollTop()
可能工作:
$('select').scrollTop(30);
And you can scroll to a particular element using this:
您可以使用以下方法滚动到特定元素:
var $s = $('select');
var optionTop = $s.find('[value="3"]').offset().top;
var selectTop = $s.offset().top;
$s.scrollTop($s.scrollTop() + (optionTop - selectTop));
Try it here: http://jsfiddle.net/kj9p4/
在这里试试:http: //jsfiddle.net/kj9p4/
Note: does not work in Chrome.
注意:在 Chrome 中不起作用。
回答by gvelkov
$("select").scrollTop($("select").find("option[value=4]").offset().top);
Just set the appropriate selectors for select element and values inside
只需为里面的 select 元素和值设置适当的选择器
回答by Lothre1
I built this extension which is a more appropriated solution to this problem. It's flexible and reusable and it's built on top of jQuery. http://jsfiddle.net/db86eu91/4/
我构建了这个扩展,它是这个问题的更合适的解决方案。它灵活且可重用,并且建立在 jQuery 之上。 http://jsfiddle.net/db86eu91/4/
;(function(){
/**
The MIT License (MIT)
Copyright (c) 2015 Márcio Reis [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
$.fn.ScrollToValue = function(target){
var $select = $(this);
if (!$select.length) return;
var value = target;
//how many pixels is the select list scrolled from the moment we run this code???
var distanceScrolledFromTop = $select.scrollTop();
//how many pixels separate the top of the page from the <select> element that we pretend to manipulate
var offsetSelect = $select.offset().top;
//assuming a offset().top of 0 on our list how many pixels separate our target option from the top of the page?
var offsetElement = $select.find('[value=' + value + ']').offset().top + distanceScrolledFromTop;
//Because the offset of our element is always bigger than the offset of our select box, we must subtract the offset of our target element by the offset of our list. That's it
$select.scrollTop(offsetElement - offsetSelect);
}
})();
回答by swedishboy
Or you can just use focus().
或者你可以只使用 focus()。
$("select").find("option[value=4]").focus();
$('select option[value="banana"]').focus();
回答by miguelangelajo
This is coffescript using jquery, (coffeescript translates directly into javascript)
这是使用jquery的coffescript,(coffeescript直接翻译成javascript)
exports.mylist_scroll_to = (value) ->
element = $("#mylist")[0]
item_height = element.scrollHeight/element.length
$("#mylist").scrollTop(item_height*(element.selectedIndex))
回答by Ivan Rolim
Although its from 2011, I was facing a large problem with Primefaces, as I use listboxes extensively.
虽然是 2011 年的,但我在使用 Primefaces 时遇到了一个大问题,因为我广泛使用列表框。
When I load items from a database in order to populate many listboxes, they werent scrolled by default.
当我从数据库加载项目以填充许多列表框时,默认情况下它们不会滚动。
I fixed this by creating a JavaScript function.
我通过创建一个 JavaScript 函数来解决这个问题。
//This function is used in primefaces listboxes with many items (which doesnt use the HTML tag 'option value="XXX" selected'). So, by default, if the current selected item is out of view, like near the bottom end, the scroll doesnt execute at all.
//此函数用于包含许多项的primefaces列表框(不使用HTML标签'option value="XXX" selected')。因此,默认情况下,如果当前选定的项目不在视图中,例如接近底端,则根本不会执行滚动。
In order to use the function below, you need to put a javascript call in your listbox, like oncomplete="autoScrollListBox('#form\:lixtboxID');"
为了使用下面的函数,您需要在列表框中放置一个 javascript 调用,例如 oncomplete="autoScrollListBox('#form\:lixtboxID');"
You can customize this function to traverse/loop through other lists, like dataTables or customized ui-******-***** names (just change them below).
您可以自定义此函数以遍历/循环其他列表,例如数据表或自定义 ui-******-***** 名称(只需在下面更改它们)。
function autoScrollListBox(id) {
var listContainer=id+' .ui-selectlistbox-listcontainer';
var listContainerList=id+' .ui-selectlistbox-listcontainer .ui-selectlistbox-list';
var listTop = $(listContainerList).offset().top;
var selectedContainer=id+ ' .ui-state-highlight';
var selectedOptionTop =$(id+' .ui-state-highlight').offset().top;
$(listContainer).animate( {scrollTop:selectedOptionTop-listTop});
}
回答by lukad
You can use the val()
function on your list. Use last item from the ones you want to display as the argument
您可以使用val()
列表中的功能。使用要显示的最后一项作为参数
$("#foo").val('5');
This will show 3-5.
这将显示 3-5。
回答by ShankarSangoli
Here is a workaround to this
这是一个解决方法
Working demo
工作演示
Code
代码
$(function(){
//Select the last option in the range which you want to scroll to
var lastOption = $("select").find("option[value=5]")
//Store the selection state
var isSelected = lastOption.is(":selected");
lastOption.attr("selected", true)//This will scroll to the option
.attr("selected", isSelected); //Restore the selection state
});