【问题标题】:Open Select using Javascript/jQuery?使用 Javascript/jQuery 打开选择?
【发布时间】:2011-01-04 03:04:54
【问题描述】:

有没有办法使用 Javascript(和 jQuery)打开选择框?

<select style="width:150px;">
    <option value="1">1</option>
    <option value="2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc arcu nunc, rhoncus ac dignissim at, rhoncus ac tellus.</option>
    <option value="3">3</option>
</select>

我必须打开我的选择,因为 IE 错误。所有版本的 IE (6,7,8) 都取消了我的选择。 据我所知,没有针对此的 CSS 错误修复。 目前我尝试执行以下操作:

var original_width = 0;
var selected_val = false;

if (jQuery.browser.msie) {
    $('select').click(function(){
        if (selected_val == false){
            if(original_width == 0)
                original_width = $(this).width();

            $(this).css({
                'position' : 'absolute',
                'width' : 'auto'
            });
        }else{
            $(this).css({
                'position' : 'relative',
                'width' : original_width
            });
            selected_val = false;
        }
    });

    $('select').blur(function(){
        $(this).css({
            'position' : 'relative',
            'width' : original_width
        });
    });

    $('select').blur(function(){
        $(this).css({
            'position' : 'relative',
            'width' : original_width
        });
    });
            
    $('select').change(function(){
        $(this).css({
            'position' : 'relative',
            'width' : original_width
        });
    });

    $('select option').click(function(){
        $(this).css({
            'position' : 'relative',
            'width' : original_width
        });
    
        selected_val = true;
    });

}

但第一次点击我的选择会改变选择的宽度,但我必须再次点击才能打开它。

【问题讨论】:

标签: javascript jquery jquery-events


【解决方案1】:

我知道这已经很老了并且已经回答了,但这在 Safari 和 iOS UIWebView 中对我有用 - 我将它隐藏了,但希望它在单击不同按钮时显示和打开。

$('#select-id').show().focus().click();

【讨论】:

  • 谢谢!经过 6 小时的反复试验,这在堆栈 JQM/Cordova/FastClick 上成功了!!!
  • On Chrome, when the select box is the target of the keydown event, this works like a charm!感谢您的提示,马特 H
【解决方案2】:

您可以使用mousedown 处理程序来捕获mousedown 事件,而不是使用click。 mousedown 在 click 之前触发,因此您可以调用 stopPropogation 来中断事件队列。

【讨论】:

    【解决方案3】:

    试试这个:

    var myDropDown=$("#myDropDown");
    var length = $('#myDropDown> option').length;
    //open dropdown
    myDropDown.attr('size',length);
    

    然后关闭:

    //close dropdown
    myDropDown.attr('size',0);
    

    【讨论】:

      【解决方案4】:

      试试这个:

      dropDown = function (elementId) {
          var dropdown = document.getElementById(elementId);
          try {
              showDropdown(dropdown);
          } catch(e) {
      
          }
          return false;
      };
      
      showDropdown = function (element) {
          var event;
          event = document.createEvent('MouseEvents');
          event.initMouseEvent('mousedown', true, true, window);
          element.dispatchEvent(event);
      };
      

      然后调用函数:

      dropDown('elementId');
      

      【讨论】:

      • 如果您使用 JQuery,也可以使用 trigger() 命令。
      • jQuery 触发器不起作用。您应该尝试创建类似答案的事件。
      【解决方案5】:

      否 jQuery 解决方案。

      <SCRIPT>
          function toggleDropdown(element){
              if(element.size == 0) {
                  element.size = element.length;
                  element.focus();
                  }
              else element.size = 0;
              }
      </SCRIPT>
      

      找到这个here。

      【讨论】:

      • 这会打开下拉菜单,但不允许在列表中进行后续箭头键导航。
      【解决方案6】:

      首先,我在 IE 中感受到了这种限制的痛苦- bleh! 只是想我也会分享这个,因为它似乎对我有用。我采取了几乎相同的方法,但在每个选择元素上。就我而言,我知道哪些列表可能包含长数据。

      我没有使选择元素成为绝对元素,而是将它们保持内联并将它们包装在带有隐藏溢出的 DIV 中,因为外观需要保持一致,而且它仅在 IE 和扩展宽度时才应用此“hack”大于当前宽度。

      要将其用于所有选择框,您可以使用以下内容:

      $("select").each(function(){ 
              $(this).IELongDropDown(); 
           });
      

      或者显然是基于每个元素的 id。 这是jquery插件:

      (function($) {
          $.fn.IELongDropDown = function(cln) {
              if (jQuery.browser.msie) { //only IE has problems with long select boxes
                  var el = this;
                  var previousWidth = el.width();
                  var divWrapper = "<div style='padding:0;margin:0;overflow:hidden;width:"+ previousWidth +"px'></div>";
                  el.wrap(divWrapper);
                  var newWidth = el.width("auto").width();
                  el.width(previousWidth);
                  if(newWidth > previousWidth) {
                      el.bind("mousedown", function(){ return el.width("auto").focus(); }); 
                      el.bind("blur", function(){ return el.width(previousWidth); });
                      el.bind("change", function(){ return el.width(previousWidth); });
                  }
              }
              return this;
          };
      })(jQuery);
      

      希望这对某人有所帮助

      【讨论】:

        【解决方案7】:

        我认为您需要从事件处理程序(单击、模糊等)返回 true,因此在您的处理程序执行后,浏览器会继续传播事件并打开选择。

        这与 href 链接类似,如果它们有 onclick 处理程序并且处理程序返回 false,则不跟随链接(浏览器在处理程序执行后停止事件)。

        编辑:根据您的评论和回答,您的处理程序似乎只有在浏览器决定打开该框后才有第一次执行的机会。
        我建议您尝试focus 事件处理程序,它可能有机会比click 处理程序更早地运行,并且可能在浏览器实际打开该框之前运行。它也更加一致(适用于鼠标和键盘导航)。

        【讨论】:

        • 我试图在我的事件操作之后返回 true - 没有成功。似乎选择在第一次单击时打开,但它并没有改变它的样式。释放鼠标后,选择将关闭并添加样式。所以我必须再次点击才能打开它。
        【解决方案8】:

        我更喜欢在 CSS 文件中设置我的 CSS,然后“addClass”,但即便如此,您的代码(部分)

           $('select').blur(function(){ 
                $(this).css({ 
                    'position' : 'relative', 
                    'width' : original_width 
                }); 
            }); 
        
            $('select').blur(function(){ 
                $(this).css({ 
                    'position' : 'relative', 
                    'width' : original_width 
                }); 
            }); 
        

        好像是重复的

        我会成功的:

        $('select').blur().css({ 
                'position' : 'relative', 
                'width' : original_width 
        }); 
        

        不确定您是否真的需要 .blur() 以及 .change() 事件(尝试将其取出,看看是否能解决您的问题...我在 IE 上经常使用 select,但似乎没有一个问题。

        【讨论】:

          【解决方案9】:

          好的,我找到了解决此问题的另一种方法。 这是修复:

          请给我反馈!我有点为自己感到骄傲;)

          $(document).ready(function() {
              if (jQuery.browser.msie) {
                      select_init();
              }
          });
          
          
          function select_init () {
              var selects = $('select');
              for (var i = 0; i < selects.length; i++) {
                  _resizeselect.init(selects[i]);
              }
          }
          
          
          var _resizeselect = {
              obj : new Array(),
              init : function (el) {
                  this.obj[el] = new resizeselect (el);
              }
          }
          
          function resizeselect (el) {
          
              this.el = el;
              this.p = el.parentNode;
              this.ht = el.parentNode.offsetHeight;
              var obj = this;
              this.set = false;
          
              el.onmousedown = function () {
                  obj.set_select("mousedown");
              }
              el.onblur = function () {
                  obj.reset_select("blur");
              }
              el.onchange = function () {
                  obj.reset_select("change");
              }
          
          }
          
          resizeselect.prototype.set_select = function (str) {
          
              if (this.set) {
                  this.set = false;
                  return;
              }
          
              this.el.style.width = "auto";
              this.el.style.position = "absolute";
              this.p.style.height = this.ht + "px";
              this.p.style.zIndex = 100;
              this.set = true;
              this.el.focus();
          }
          
          resizeselect.prototype.reset_select = function (str) {
              this.el.style.width = "";
              this.el.style.position = "";
              this.p.style.height = "";
              this.p.style.zIndex = 1;
              this.set = false;
              window.focus();
          }
          

          【讨论】:

            【解决方案10】:

            mousedown 事件在单击事件之前引发:

            1. first mousedown raise -> 将宽度设置为“auto”(如果下拉菜单的状态为“close”)
            2. 单击 raise -> 将下拉列表的状态存储在 var 中:'open'
            3. 我们选择一个值,第二次 mousedown 被提升:无事可做
            4. 点击 raise -> 我们需要恢复下拉菜单的原始宽度并将 var 的状态更改为:'close'

            如果用户在下拉菜单外点击,则需要使用 blur 和 change 事件来关闭下拉菜单。

            这里是 Brendan 代码的完整解决方案:

            (function ($) {
            var open = {}
            $.fn.IELongDropDown = function (cln) {
                if (jQuery.browser.msie) { //only IE has problems with long select boxes
                    var el = this;
                    var id = el.attr('id');
                    var margin = 2; //Need to set a margin however the arrow is cut
                    var previousWidth = el.width() + margin;
                    var divWrapper = "<div style='padding:0;margin:0;overflow:hidden;width:" + previousWidth + "px'></div>";
                    el.wrap(divWrapper);
                    var newWidth = el.width("auto").width();
                    el.width(previousWidth);
                    if (newWidth > previousWidth) {
                        el.mousedown(function () {
                            if (!open[id]) {
                                el.width("auto");
                                el.focus();
                            }
                        });
                        el.click(function () {
                            if (!open[id])
                                open[id] = true;
                            else {
                                open[id] = false;
                                return el.width(previousWidth);
                            }
                        });
                        el.blur(function () {
                            open[id] = false;
                            return el.width(previousWidth);
                        });
                        el.change(function () {
                            open[id] = false;
                            return el.width(previousWidth);
                        });
                    }
                }
                return this;
            };
            })(jQuery);
            

            调用函数:

            <script type="text/javascript" language="javascript">
                $(document).ready(function () {
                    $('#mydropdownlist').IELongDropDown();
                });
            </script>
            

            【讨论】:

              【解决方案11】:

              您无法打开选择列表,但您可以通过单击或任何其他您想要的事件更改选择列表的大小来实现

                      $("#drpdwn").mousedown(bodyevent);
                      function bodyevent()
                      {
                          console.log("size changed");
                          $(this).attr('size',3);
                      }
                      $("#drpdwn").focus(function()
                      {
                          //alert("txt  clicked from ");
                          var $el = $("#drpdwn");
                          var offset = $el.offset();
                          var event = jQuery.Event( "mousedown", {
                              which: 1,
                              pageX: offset.left,
                              pageY: offset.top
                          });
                          $el.trigger(event);
                      });
              

              【讨论】:

                【解决方案12】:

                您也可以使用select2 插件并执行以下操作:

                $(element_select).focus(); 
                $(element_select).select2('open').trigger('open');
                

                它在 Firefox 79.0 版中非常适合我

                【讨论】:

                  【解决方案13】:

                  我为这个问题找到了一个替代解决方案。只需向您的选择框添加一个主题,例如 Selectize.js,它会将您的选择框转换为 ul li html 标签,但可以用作选择框。您可以在 jquery 事件中轻松隐藏 show ul li。

                  【讨论】:

                    猜你喜欢
                    • 2011-10-07
                    • 1970-01-01
                    • 2012-05-14
                    • 2013-10-26
                    • 1970-01-01
                    • 1970-01-01
                    • 2011-07-06
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多