这个问题演变为阻止在Enter键上打开下拉菜单。如您所见,当标签输入具有焦点时,按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>
答案 0 :(得分:0)
在阅读了有关event listeners的一些文档后,我编写了此代码,该代码仅在单击叉形以删除标签时才有效,请指定是否希望在单击整个标签时阻止下拉菜单,会看一下,这里是代码,基本上,我们正在听select2:unselecting
事件,并通过阻止触发其适当的打开事件来阻止显示下拉菜单:
$(".tags").on('select2:unselecting', function (e) {
$(".tags").on('select2:opening', function (e) {
e.preventDefault();
$(".tags").off('select2:opening');
});
});
下面的工作片段:
$(".tags").select2({
tags: true,
width: '100%'
});
$(".tags").on('select2:unselecting', function (e) {
$(".tags").on('select2:opening', function (e) {
e.preventDefault();
$(".tags").off('select2:opening');
});
});
<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>