【问题标题】:Select2: Remove item from selection when clicking anywhere on item, instead of crossSelect2:单击项目上的任意位置时从选择中删除项目,而不是交叉
【发布时间】:2017-11-20 23:57:51
【问题描述】:

是否有一种干净的方法可以删除多选框中 select2 项目左侧的“十字”,并为整个按钮启用功能(单击时删除所选项目)?见图片;我希望能够单击绿色突出显示按钮中的任意位置,而不是单击红色突出显示的十字来删除该项目。

默认功能是打开选择下拉菜单——可以改为单击文本框中的任意位置。另一方面,十字架很小,很容易错过点击。

如果没有“干净”或“有意”的方法来解决这个问题,欢迎提出解决方法的建议。

【问题讨论】:

    标签: javascript jquery jquery-select2


    【解决方案1】:

    在不修改源代码的情况下执行此操作的另一种方法是让“x”的足迹占据元素的大小:

    /* pillbox li container item */
    .select2-selection__choice {
        position: relative;
        padding-left: 15px; /* to account for the 'x' no longer taking up space */
    }
    
    /* the 'x' */
    .select2-selection__choice__remove {
        position: absolute;
        left: 0; right: 0; /* to fill width */
        padding-left: 5px; /* whatever matches your pillbox padding */
    
        color: transparent !important; /* hide the x */
    }
    

    【讨论】:

      【解决方案2】:

      好的,整理好了。下载未缩小的 JS (4.0.6-rc.0) 并执行以下操作:


      为了去掉“十字架”,改变了这个

      MultipleSelection.prototype.selectionContainer = function () {
              var $container = $(
              '<li class="select2-selection__choice">' +
                  '<span class="select2-selection__choice__remove" role="presentation">' +
                      '&times;' +
                  '</span>' +
              '</li>'
          );
          return $container;
      };
      

      到这里

      MultipleSelection.prototype.selectionContainer = function () {
              var $container = $(
              '<li class="select2-selection__choice"></li>'
          );
          return $container;
      };
      

      要添加“取消选择标签点击”,添加此点击

      this.$selection.on(
          'click',
          '.select2-selection__choice',
          function (evt) {
              // Ignore the event if it is disabled
              if (self.options.get('disabled')) {
                  return;
              }
      
              var data = Utils.GetData(this, 'data');
      
              self.trigger('unselect', {originalEvent: evt, data: data})
      
              evt.stopPropagation()
          }
      )
      

      函数内部

      MultipleSelection.prototype.bind = function (container, $container) {
          ...
      }
      

      (非常类似于其中用于正常处理“交叉”点击的现有代码)

      最后,将相关的 css 从 cursor: default 调整为 cursor: pointer

      最终结果:

      【讨论】:

      • M.chrichton 刚刚发现您的帖子帮助我解决了我的问题。感谢您的精彩帖子。
      • 感谢您的赞誉,但如果您正确拼写我的名字,我将更加感激;)哦,并且...对问题/答案进行了投票。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      • 1970-01-01
      相关资源
      最近更新 更多