【问题标题】:How to scroll a select list with JavaScript or jQuery?如何使用 JavaScript 或 jQuery 滚动选择列表?
【发布时间】:2011-08-26 13:52:47
【问题描述】:

我有一个选择标签:

           <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> 

现在它显示前 3 个选项, 如何使用 jQuery 或纯 JavaScript 滚动查看 3-5 或 4-6 中的元素?

【问题讨论】:

  • 在 Chrome 中,select 滚动框将自动滚动以突出显示选定的项目(但不会进一步)。您可以使用 JavaScript 选择然后取消选择特定的 option 以强制滚动。
  • 对我来说,在 Linux 上使用 Chrome 41,如果它是 display:none 或父项是 display:none,则在页面加载期间选择不会自动滚动。即使 css 样式设置为 display:something (e.g. parent set display:block) 在 body 的加载期间它也不能正确滚动。设置后将 selectedIndex 重新设置为自身,例如display:block 在相关父级上,导致滚动发生。

标签: javascript jquery html


【解决方案1】:

.scrollTop() 可能有效:

$('select').scrollTop(30);

您可以使用以下方法滚动到特定元素:

var $s = $('select');

var optionTop = $s.find('[value="3"]').offset().top;
var selectTop = $s.offset().top;

$s.scrollTop($s.scrollTop() + (optionTop - selectTop));

在这里试试:http://jsfiddle.net/kj9p4/

注意:在 Chrome 中不起作用。

【讨论】:

  • 这行得通,现在是最糟糕的部分 :) 计算要滚动多少像素。
  • 我已经添加了如何滚动到特定元素的代码和 jsfiddle;我已经在 Firefox 中测试过这个
  • 您在 Chrome 中尝试过吗?那里对我不起作用。似乎与获取选项元素的偏移量有关。
  • 在 Safari 6 中也不起作用。在选项上调用 offset() 会为顶部和左侧返回 0。
  • 在 chrome 版本 49.0.2623.87 m 中工作正常
【解决方案2】:
 $("select").scrollTop($("select").find("option[value=4]").offset().top);

只需为内部的选择元素和值设置适当的选择器

【讨论】:

  • 对我来说很好,但你需要减去选择本身的偏移量,即 - $('select').offset().top
【解决方案3】:

我构建了这个扩展,它是解决这个问题的更合适的解决方案。它灵活且可重用,并且构建在 jQuery 之上。 http://jsfiddle.net/db86eu91/4/

;(function(){
/**
The MIT License (MIT)

Copyright (c) 2015 Márcio Reis marcio.reis@outlook.com

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);
}

})();

【讨论】:

  • 如果您是从bootstrap modal 那里执行此操作,您必须小心,因为时间将是一个问题。在shown 事件中进行此调用。
【解决方案4】:

这是使用jquery的coffescript,(coffeescript直接翻译成javascript)

exports.mylist_scroll_to  = (value) ->
    element = $("#mylist")[0]
    item_height = element.scrollHeight/element.length
    $("#mylist").scrollTop(item_height*(element.selectedIndex))

【讨论】:

    【解决方案5】:

    或者你可以只使用focus()。

    $("select").find("option[value=4]").focus();
    $('select option[value="banana"]').focus();
    

    【讨论】:

    • 滚动到列表顶部:$('select option:first').focus()
    【解决方案6】:

    您可以使用列表中的val() 函数。使用要显示的最后一项作为参数

    $("#foo").val('5');
    

    这将显示 3-5。

    【讨论】:

    • 在这种情况下将选择第 5 个元素。
    【解决方案7】:

    这里有一个解决方法

    工作demo

    代码

    $(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
    });
    

    【讨论】:

      【解决方案8】:

      虽然它是从 2011 年开始的,但由于我广泛使用列表框,因此我在使用 Primefaces 时遇到了一个大问题。

      当我从数据库加载项目以填充许多列表框时,默认情况下它们不会滚动。

      我通过创建一个 JavaScript 函数解决了这个问题。

      //这个函数用于有很多项目的primefaces列表框(不使用HTML标签'option value="XXX" selected')。因此,默认情况下,如果当前选定的项目不在视线范围内,例如靠近底端,则根本不会执行滚动。

      为了使用下面的功能,你需要在你的列表框里放一个javascript调用,比如oncomplete="autoScrollListBox('#form\:lixtboxID');"

      您可以自定义此函数以遍历/循环其他列表,例如 dataTables 或自定义的 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});
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-08
        • 1970-01-01
        • 1970-01-01
        • 2019-02-06
        • 1970-01-01
        • 2022-11-23
        • 2015-11-01
        • 2011-01-11
        相关资源
        最近更新 更多