代码之家  ›  专栏  ›  技术社区  ›  Scott

选择框在IE7中收缩,但不是IE6或IE8

  •  5
  • Scott  · 技术社区  · 16 年前

    我在IE7中遇到了jquery和select框的问题。当我设置一个选择框的宽度,然后使用jquery在第一个选择框发生更改时重新填充这些项时,第二个选择框将根据设置的宽度进行缩减。

    例如: 下面的代码使用两个选择框。当第一个选择框触发更改事件时,它将删除所有第二个选择框并添加一些新值。如果删除第二个选择框的样式属性,则满足所需的行为。保留样式属性后,第二个选择框将变得越来越小,并最终消失。

    这只发生在IE7中。

    代码如下:

    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>test</title>
        <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $("#selOne").change(function(){
                    //Clear out the current service list
                    $("#selTwo option").each(function(){
                        $(this).remove();
                    });
    
                    for(var i=0; i < 10; i++){
                         var newOption = '<option value="'+ i +'">'+ i +'</option>';
                         $("#selTwo").append(newOption);
                    }
                });
            });
        </script>
    
    </head>
    <body>
        <select id="selOne" class="number req" style="width: 90%;">
             <option value="" selected="selected">Initial Select</option>
             <option value="">a</option>
             <option value="">b</option>
             <option value="">c</option>
    
        </select>
        <select id="selTwo" class="number req" style="width: 90%;">
             <option value="" selected="selected">These should update</option>
             <option value="">100</option>
             <option value="">101</option>
             <option value="">102</option>
        </select>
    </body>
    </html>
    

    如何仍然指定宽度,但不将选择框缩小为零?唯一的方法是以像素为单位的绝对宽度吗?

    3 回复  |  直到 12 年前
        1
  •  7
  •   Scott    16 年前

    以下代码获取第二个选择框以保持正确的大小:

            $("#selOne").change(function(){
                //Clear out the current service list
                $("#selTwo option").each(function(){
                    $(this).remove();
                });
    
                /* IE7 Fix: reset the width based on pixels
                    It doesn't matter to how many, just that
                    the width is in pixels
                */
                $("#selTwo").css("width","1px");
    
                for(var i=0; i < 10; i++){
                     var newOption = '<option value="'+ i +'">'+ i +'</option>';
                     $("#selTwo").append(newOption);
                }
    
                /*IE7 FIX: rest the width back to our desired percent */
                $("#selTwo").css("width","90%");
            });
    
        2
  •  0
  •   jitter    16 年前

    你能试试这个吗?

    $("<option>").attr("value", i).text(i).appendTo("#selTwo"); 
    
        3
  •  0
  •   Shahin    12 年前

    在我的例子中,我只是在IE7中使用css hack,如下所示-

    select.number { *width: 280px !important; }
    

    注意:请改为以像素为单位的等效宽度。