Chrome中多选列表上的jQuery设置道具("已选",真)只能使用一次

kav*_*vun 4 javascript jquery scroll google-chrome multi-select

尝试将选择列表选项设置为选中以将选择列表滚动到该选项时,它适用于除Chrome之外的所有浏览器.在Chrome中它可以运行一次,但连续几次在Chrome中无效.如何确保在选择列表中设置选项的选定属性会将该选项滚动到视图中?

这是我的问题的一个例子 - http://jsfiddle.net/Z2rQG/

我用来选择列表中的选项以将其滚动到视图的代码如下:

(function ($) {
    $.fn.scrollToOption = function (option) {
        var _option = $(option, this);
        // if option is in list
        if(_option) {
            // store the selection state
            var isSelected = _option.is(":selected");

            _option.prop("selected", true); // scroll to the option
            _option.prop("selected", isSelected);  // restore the selection state
        }
        return this;
    };
})(jQuery); 
Run Code Online (Sandbox Code Playgroud)

编辑:我也尝试过scrollTo jQuery插件,这在Chrome中不起作用.这是一个例子 - http://jsfiddle.net/kavun/TW4XK/

编辑:这是我想要做的更清楚的例子.从选择列表中选择两个选项,并将列表滚动到最后选择的选项.这适用于除Chrome和Safari之外的所有浏览器.在Chrome中,第一个选项滚动到选项,但第二个选项$('#select option[value=""].prop('selected', true); 不滚动列表 - http://jsfiddle.net/kavun/uhnZH/

Tim*_*own 13

当选择多个选项时,浏览器行为与滚动到视图中的选项不一致.但是,选择使用其selected属性的选项以及设置元素的selectedIndex属性<select>似乎可以确保选择在所有主要浏览器中滚动到正确的位置.使用此选项,您可以获得正确的垂直滚动,选择所需的选项,然后手动滚动选择.

Opera似乎并不完全支持scrollTopselect元素,因此这个解决方案在Opera中不起作用.

演示:http://jsfiddle.net/uhnZH/10/

码:

function selectAndScrollToOption(select, option) {
    $select = $(select);

    // Store the currently selected options
    var $selectedOptions = $select.find("option:selected");

    // Select the new option using its selected property and selectedIndex.
    // This seems to make the select scroll to the desired place in all major
    // browsers
    option.selected = true; // Required for old IE
    select.selectedIndex = option.index;

    // Measure the vertical scrolling
    var scrollTop = $select.scrollTop();

    // Re-select the original options
    $selectedOptions.prop("selected", true);

    // Scroll to the correct place
    $select.scrollTop(scrollTop);
}
Run Code Online (Sandbox Code Playgroud)