【发布时间】:2022-04-23 02:59:20
【问题描述】:
这个问题演变成阻止下拉菜单在输入键按下时打开。如您所见,当您在标签输入具有焦点时按 Enter 键时,我的丑陋解决方案会使用 setTimeout 关闭下拉列表。如何防止它在进入时完全打开,而不是在打开后关闭它?
以下是一些可能有用的事件: https://select2.org/programmatic-control/events
var tagClick = false;
$(document).on('mousedown touchstart', '.tag', function(e) {
var $self = $(this);
tagClick = true;
});
$(document).on('click', '.tag', function(e) {
var $self = $(this);
var $input = $self.find('input');
$input.select();
});
$(document).on('blur', '.tag input', function(e) {
var $self = $(this);
$self.attr('value', $self.val());
setTimeout(function() {
$(".tags").select2('close');
}, 100);
// Save to db here
});
$(document).on('keydown', '.tag input', function(e) {
var nl = e.keyCode == 13; // is enter?
var $self = $(this);
if( nl )
{
$self.blur();
}
});
$(".tags").select2({
templateSelection: function(argSelection)
{
return $.parseHTML('<span class="tag">'+(argSelection.name || argSelection.text)+'<input type="text" value="" /></span>');
},
tags: true,
width: '100%'
})
.on('select2:opening', function (e) {
var $self = $(this);
if( tagClick )
{
e.preventDefault();
tagClick = false;
}
})
.tag input {
width: 50px;
height: 10px;
margin-left: 5px;
}
.tag input[value=""]:not(:focus) {
width: 0;
margin-left: 0;
background: transparent;
border: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>
<select class="tags" multiple="multiple">
<option selected="selected">orange</option>
<option>white</option>
<option selected="selected">purple</option>
</select>
【问题讨论】:
标签: javascript jquery jquery-select2