首页 > 解决方案 > Select2 在每次选择时将当前选择范围滚动到底部(closeOnSelect = False)

问题描述

JSFiddle:http: //jsfiddle.net/xpvt214o/776660/

我有一个固定高度为 1 行的多选select2控件。当我选择新的多个项目时,它们会被添加,但跨度不会将光标移动到“当前”框的末尾。当前选择器卡在当前行。一旦我离开选择过程,它只会移动到最后。

我尝试了这段代码,您可以对其进行评论以查看原始问题:

/* Scroll CurrSel SPAN to bottom on every Select2 Select event */
/* Comment/Toggle this ON/OFF for testing */
$('#dropdown').on("select2:selecting", function(e) { 
    var currselspan = $('#dropdown').next().find('.select2-selection--multiple').first();
    console.log('scrollTop = ' + $(currselspan).scrollTop() + ' scrollHeight = ' + $(currselspan).prop('scrollHeight'));
    $(currselspan).scrollTop($(currselspan).prop('scrollHeight'));
});

这是一个改进,但仍然存在一个问题:新条目第一次进入下一行时,当前选择范围不会滚动。它仅在换行符进入后才开始滚动。

目标:任何时候“换行条目进入”时,都会自动滚动到当前选择的末尾。

标签: jqueryjquery-select2

解决方案


只需在您的方法中添加以下行。

$(".select2-selection--multiple input").focus();

所以你的方法将是

$('#dropdown').on("select2:selecting", function(e) { 
    var currselspan = $('#dropdown').next().find('.select2-selection--multiple').first();
    console.log('scrollTop = ' + $(currselspan).scrollTop() + ' scrollHeight = ' + $(currselspan).prop('scrollHeight'));
    $(currselspan).scrollTop($(currselspan).prop('scrollHeight'));
    $(".select2-selection--multiple input").focus();
});

你可以在这里测试它.. http://jsfiddle.net/xpvt214o/776765/


推荐阅读