IT Share you

IE에서 콘텐츠를 자르는 고정 너비가있는 드롭 다운 선택

shareyou 2021. 1. 8. 21:44
반응형

IE에서 콘텐츠를 자르는 고정 너비가있는 드롭 다운 선택


문제:

선택 항목의 일부 항목을 완전히 표시하려면 지정된 너비 인 145px 이상이 필요합니다.

Firefox 동작 : 선택을 클릭하면 가장 긴 요소의 너비에 맞게 조정 된 드롭 다운 요소 목록이 표시됩니다.

IE6 및 IE7 동작 : 선택을 클릭하면 145px 너비로 제한된 드롭 다운 요소 목록이 표시되어 더 긴 요소를 읽을 수 없습니다.

현재 UI에서는이 드롭 다운을 145px에 맞추고 더 긴 설명이있는 항목을 호스팅해야합니다.

IE 문제 해결에 대한 조언이 있습니까?

목록이 확장 된 경우에도 상단 요소의 너비는 145px로 유지되어야합니다.

감사합니다!

CSS :

select.center_pull {
    background:#eeeeee none repeat scroll 0 0;
    border:1px solid #7E7E7E;
    color:#333333;
    font-size:12px;
    margin-bottom:4px;
    margin-right:4px;
    margin-top:4px;
    width:145px;
}

다음은 선택 입력 코드입니다 (현재 backend_dropbox 스타일에 대한 정의는 없음).

<select id="select_1" class="center_pull backend_dropbox" name="select_1">
<option value="-1" selected="selected">Browse options</option>
<option value="-1">------------------------------------</option>
<option value="224">Option 1</option>
<option value="234">Longer title for option 2</option>
<option value="242">Very long and extensively descriptive title for option 3</option>
</select>

브라우저에서 빠르게 테스트하려는 경우 전체 html 페이지 :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>dropdown test</title>

<style type="text/css">
<!--
select.center_pull {
    background:#eeeeee none repeat scroll 0 0;
    border:1px solid #7E7E7E;
    color:#333333;
    font-size:12px;
    margin-bottom:4px;
    margin-right:4px;
    margin-top:4px;
    width:145px;
}
-->
</style>
</head>

<body>
<p>Select width test</p>
<form id="form1" name="form1" method="post" action="">
<select id="select_1" class="center_pull backend_dropbox" name="select_1">
<option value="-1" selected="selected">Browse options</option>
<option value="-1">------------------------------------</option>
<option value="224">Option 1</option>
<option value="234">Longer title for option 2</option>
<option value="242">Very long and extensively descriptive title for option 3</option>
</select>
</form>
</body>
</html>

IE 8의 경우 간단한 순수 CSS 기반 솔루션이 있습니다.

select:focus {
    width: auto;
    position: relative;
}

(선택 상자가 너비가 고정 된 컨테이너의 자식 인 경우 위치 속성을 설정해야합니다.)

불행히도 IE 7 이하에서는 : focus 선택기를 지원하지 않습니다.


이 문제에 대해 Google을 수행했지만 최상의 솔루션을 찾지 못했기 때문에 모든 브라우저에서 제대로 작동하는 솔루션을 만들었습니다.

페이지로드시 badFixSelectBoxDataWidthIE () 함수를 호출하면됩니다.

function badFixSelectBoxDataWidthIE(){
    if ($.browser.msie){
      $('select').each(function(){
    if($(this).attr('multiple')== false){
      $(this)
          .mousedown(function(){
               if($(this).css("width") != "auto") {
                   var width = $(this).width();
                   $(this).data("origWidth", $(this).css("width"))
                          .css("width", "auto");
                   /* if the width is now less than before then undo */
                   if($(this).width() < width) {
        $(this).unbind('mousedown');
                       $(this).css("width", $(this).data("origWidth"));
                   }
               }
           })
           /* Handle blur if the user does not change the value */
           .blur(function(){
               $(this).css("width", $(this).data("origWidth"));

           })
           /* Handle change of the user does change the value */
           .change(function(){
               $(this).css("width", $(this).data("origWidth"));

           });
        }
      });
    }
    }

다음은 도움이되는 작은 스크립트입니다.

http://www.icant.co.uk/forreview/tamingselect/


자바 스크립트가없는 간단한 솔루션의 경우 요구 사항에 따라 텍스트가있는 <option>에 제목 속성을 추가하는 것으로 충분할 수 있습니다.

<option value="242" title="Very long and extensively descriptive text">
  Very long and extensively descriptive text
</option>

이렇게하면 <select>의 너비에 관계없이 <option>을 가리키면 도구 설명 방식으로 잘린 텍스트가 표시됩니다.

IE7 +에서 작동합니다.


자바 스크립트가 무료가 아닙니다. 두렵지 만 jQuery를 사용하여 아주 작게 만들 수있었습니다.

$('#del_select').mouseenter(function () {

    $(this).css("width","auto");

});

$('#del_select').mouseout(function () {

    $(this).css("width","170px");

}); 

이 플러그인을 jquery에 사용할 수 있습니다.)

http://plugins.jquery.com/project/skinner

$(function(){
          $('.select1').skinner({'width':'200px'});
});

불필요한 각 루프를 제거하는 MainMa 및 user558204 (감사합니다)의 코드에 대한 작지만 유용한 업데이트는 두 번 이상 사용되므로 각 이벤트 처리기의 변수에 $ (this) 복사본을 저장합니다. 같은 동작을했기 때문에 이벤트를 흐리게하고 변경합니다.

예, 드롭 다운 옵션이 아닌 선택 요소의 크기를 조정하므로 여전히 완벽하지 않습니다. 하지만 이로 인해 피클에서 벗어날 수있었습니다. 저는 (매우, 매우 안타깝게도) 여전히 비즈니스 전반에 걸쳐 IE6 지배적 인 사용자 기반을 지원해야합니다.

// IE test from from: https://gist.github.com/527683
var ie = (function () {
  var undef, v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');
  while (
    div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
    all[0]
  );
  return v > 4 ? v : undef;
} ());


function badFixSelectBoxDataWidthIE() {
  if (ie < 9) {
    $('select').not('[multiple]')
      .mousedown(function() {
        var t = $(this);
        if (t.css("width") != "auto") {
          var width = t.width();
          t.data("ow", t.css("width")).css("width", "auto");

          // If the width is now less than before then undo
          if (t.width() < width) {
            t.unbind('mousedown');
            t.css("width", t.data("ow"));
          }
        }
      })

      //blur or change if the user does change the value
      .bind('blur change', function() {
        var t = $(this);
        t.css("width", t.data("ow"));
      });
  }
}

다른 접근 방식 :

  1. 선택 대신 편집 상자로 설정하고 비활성화되어 아무도 수동으로 입력하거나 선택 후 내용을 변경할 수 없습니다.
  2. 선택한 옵션의 ID를 포함하는 또 다른 숨겨진 편집 (아래 설명)
  3. 버튼 [..]을 만들고 아래 div를 표시하도록 스크립트
  4. 편집 상자 아래 또는 근처에 절대 위치로 숨겨진 div 만들기
  5. 해당 div에 스타일 size = "6"(드롭 다운 목록이 아닌 6 개의 옵션과 스크롤바 표시) 및 버튼 "선택"및 "취소"를 포함하도록 선택합니다.
  6. 너비에 스타일을 지정하지 마십시오. 전체가 가장 넓은 옵션의 너비 나 버튼에 원하는 패딩을 더한 것으로 가정합니다.
  7. "선택"버튼을 스크립팅하여 선택한 옵션의 ID를 숨겨진 편집 상자에 복사하고 그 값을 보이는 편집 상자에 복사하고 div를 다시 숨 깁니다.

총 4 개의 간단한 자바 스크립트 명령어.


나는 이것에 대한 매우 간단한 수정을 찾았습니다. 에서 <select>html 요소 이러한 속성을 추가 :

onmouseover="autoWidth(this)" 
onblur="resetWidth(this)" 

따라서 사용자가 해당 너비를 클릭 할 때마다 너비가 자동으로 확장되고 사용자가 선택 상자를 벗어나면 너비가 원래대로 재설정됩니다.


비슷한 해결책은 여기에서 jquery를 사용하여 초점 (또는 mouseenter) 자동 너비를 설정하고 흐림 (또는 mouseleave) 때 원래 너비를 다시 설정할 수 있습니다 http://css-tricks.com/select-cuts-off-options-in -ie-fix / .


for (i=1;i<=5;i++){
   idname = "Usert" + i;
   document.getElementById(idname).style.width = "100%";

}

너비가 올바르게 표시되지 않을 때 드롭 다운 목록을 표시하기 위해이 방법을 사용했습니다.

IE6, Firefox 및 Chrome에서 작동합니다.


완전한 jQuery 플러그인을 사용할 수 있습니다. 데모 페이지를 확인하십시오. http://powerkiki.github.com/ie_expand_select_width/

면책 조항 : 코드를 작성했습니다. 패치 환영


왜 드롭 다운 목록에서 이벤트 위로 마우스를 원하는 사람이 있습니까? 드롭 다운 목록이 작동하는 방식으로 IE8을 조작하는 방법은 다음과 같습니다.

먼저 IE8에서만 함수를 전달하고 있는지 확인합니다.

    var isIE8 = $.browser.version.substring(0, 2) === "8.";
    if (isIE8) {
       //fix me code
    }

그런 다음 선택 항목이 콘텐츠 영역 외부로 확장 될 수 있도록 div의 드롭 다운 목록을 올바른 구조로 래핑 한 다음 도우미 함수를 호출합니다.

        var isIE8 = $.browser.version.substring(0, 2) === "8.";
    if (isIE8) {
        $('select').wrap('<div class="wrapper" style="position:relative; display: inline-block; float: left;"></div>').css('position', 'absolute');

        //helper function for fix
        ddlFix();
    }

이제 이벤트에. IE8은 어떤 이유로 든 초점을 맞춘 후 이벤트를 던지기 때문에 IE는 확장을 시도 할 때 렌더링 후 위젯을 닫습니다. 해결 방법은 가장 긴 옵션 텍스트를 기반으로 자동 확장되는 클래스 'focusin''focusin' 에 바인딩 하는 것입니다. 그런 다음 기본값을 지나서 축소되지 않는 일정한 최소 너비를 보장하기 위해 현재 선택 목록 너비를 가져 와서 'onchange' 바인딩 의 드롭 다운 목록 최소 너비 속성으로 설정할 수 있습니다 .

    function ddlFix() {
    var minWidth;

    $('select')

    .each(function () {
        minWidth = $(this).width();
        $(this).css('min-width', minWidth);
    })
    .bind('focusin', function () {
        $(this).addClass('expand');
    })
    .change(function () {
        $(this).css('width', minWidth);
    })
    .bind('focusout', function () {
        $(this).removeClass('expand');
    });
}

마지막으로 스타일 시트에이 클래스를 추가해야합니다.

 select:focus, select.expand {
    width: auto;
}

자바 스크립트가 무료가 아닙니다. 제 솔루션에는 js 라이브러리가 필요하지만 모든 파일을 사용하는 대신 필요한 파일 만 사용할 수 있습니다. 프로젝트에 이미 YUI를 사용하고 있거나 어떤 파일을 결정하는 사용자에게 가장 적합 할 수 있습니다. 사용할 하나. http://ciitronian.com/blog/programming/yui-button-mimicking-native-select-dropdown-avoid-width-problem/을 살펴보십시오 .

내 블로그 게시물은 또한 다른 솔루션에 대해서도 설명합니다. 하나는 여기 stackoverflow에서 다시 참조됩니다. 내 자신의 SELECT 요소를 만들기 위해 돌아간 이유는 간단한 이유 때문입니다. 나는 mouseover 확장 이벤트를 좋아하지 않습니다. 다른 사람에게도 도움이된다면!


jquery BalusC의 솔루션이 개선되었습니다. 또한 사용 : 여기에 Brad Robertson의 의견 .

이것을 .js에 넣고 원하는 콤보에 와이드 클래스를 사용하고 ID를 부여하기 위해 위조하지 마십시오. onload (또는 documentReady 등)에서 함수를 호출합니다.
간단하게 :)
콤보에 대해 정의한 너비를 최소 길이로 사용합니다.

function fixIeCombos() {
    if ($.browser.msie && $.browser.version < 9) {
    var style = $('<style>select.expand { width: auto; }</style>');
    $('html > head').append(style);

    var defaultWidth = "200";

    // get predefined combo's widths.
    var widths = new Array();
    $('select.wide').each(function() {
        var width = $(this).width();
        if (!width) {
        width = defaultWidth;
        }
        widths[$(this).attr('id')] = width;
    });

    $('select.wide')
    .bind('focus mouseover', function() {
        // We're going to do the expansion only if the resultant size is bigger
        // than the original size of the combo.
        // In order to find out the resultant size, we first clon the combo as
        // a hidden element, add to the dom, and then test the width.
        var originalWidth = widths[$(this).attr('id')];

        var $selectClone = $(this).clone();
        $selectClone.addClass('expand').hide();
        $(this).after( $selectClone );
        var expandedWidth = $selectClone.width()
        $selectClone.remove();
        if (expandedWidth > originalWidth) {
        $(this).addClass('expand').removeClass('clicked');
        }
    })
    .bind('click', function() {
        $(this).toggleClass('clicked'); 
    })
    .bind('mouseout', function() {
        if (!$(this).hasClass('clicked')) {
        $(this).removeClass('expand');
        }
    })
    .bind('blur', function() {
        $(this).removeClass('expand clicked');
    })
    }
}

IE, Chrome, FF 및 Safari의 모든 버전에서 테스트되었습니다.

// 자바 스크립트 코드

    <script type="text/javascript">
    <!-- begin hiding
    function expandSELECT(sel) {
      sel.style.width = '';
    }
    function contractSELECT(sel) {
      sel.style.width = '100px';
    }
    // end hiding -->
    </script>

// Html code

    <select name="sideeffect" id="sideeffect"  style="width:100px;" onfocus="expandSELECT(this);" onblur="contractSELECT(this);" >
      <option value="0" selected="selected" readonly="readonly">Select</option>
    <option value="1" >Apple</option>
    <option value="2" >Orange + Banana + Grapes</option>

이것에 대한 또 다른 공헌이 있습니다. 도움이 될 수 있도록 잠시 전에 작성했습니다. http://dpatrickcaldwell.blogspot.com/2011/06/giantdropdown-jquery-plugin-for-styling.html

숨겨진 선택 요소로 뒷받침되는 스타일링 가능한 정렬되지 않은 목록을 만드는 jquery 플러그인입니다.

소스는 github에 있습니다 : https://github.com/tncbbthositg/GiantDropdown

SELECT로 할 수없는 UL에서 동작과 스타일을 처리 할 수 ​​있습니다. 선택 목록이 여전히 존재하기 때문에 다른 모든 항목은 동일해야하며 숨겨져 있지만 UL은이를 백업 데이터 저장소로 사용합니다 (원하는 경우).


페이지에 동적으로 추가 한 선택 항목과 함께 작동하기를 원했기 때문에 많은 실험 끝에 "fixedwidth"클래스를 사용하여 수행하려는 모든 선택 항목을 제공하고 다음 CSS를 추가했습니다.

table#System_table select.fixedwidth { width: 10em; }
table#System_table select.fixedwidth.clicked { width: auto; }

그리고이 코드

<!--[if lt IE 9]>
    <script type="text/javascript">
        jQuery(document).ready(function() {
            jQuery(document).on(
              {
                'mouseenter': function(event) {
                    jQuery(this).addClass('clicked');
                    },
                'focusout change blur': function() {
                    jQuery(this).removeClass('clicked');
                    }
              }, 'select.fixedwidth');
        });
    </script>
<![endif]-->

몇 가지 유의할 사항 :

  • 내 선택 항목이 모두 테이블에 있다는 사실에도 불구하고 "on"을 수행해야 jQuery(document).on했습니다.jQuery('table#System_table').on
  • jQuery 문서에서 " mouseleave"대신 " " 을 사용한다고 말 했음에도 불구하고 blurIE7에서 마우스를 드롭 다운 목록 아래로 이동하면 mouseleave이벤트가 발생하지만 blur.

실제로 작동하는 솔루션이 있습니다.

IE의 너비를 설정하고 페이지 레이아웃을 엉망으로 만들지 않으며이 페이지의 다른 솔루션과 같이 선택 옵션 위에 마우스를 올려도 드롭 다운을 닫지 않습니다.

그러나 margin-right선택 필드에 대해 가지고있는 것과 일치하도록 값 및 너비 값 을 변경해야 합니다.

또한 당신은을 대체 할 수 $('select')$('#Your_Select_ID_HERE')단지 특정 선택 필드에 영향을에. 또한 아래 코드에서했던 것처럼 DOM 사용하여 fixIESelect()본문 onload또는 jQuery를 통해 함수를 호출해야 ready합니다.

//////////////////////////
// FIX IE SELECT INPUT //
/////////////////////////
window.fixIESelect_clickset = false;
function fixIESelect()
{
 if ($.browser.msie)
 {
  $('select').mouseenter(function ()
  {
   $(this).css("width","auto");
   $(this).css("margin-right","-100");
  });
  $('select').bind('click focus',function ()
  {
   window.fixIESelect_clickset = true;
  });
  $('select').mouseout(function ()
  {
   if(window.fixIESelect_clickset != true)
   {
    $(this).css("width","93px");
    window.fixIESelect_clickset = false;
   }
  });
  $('select').bind('blur change',function ()
  {
   $(this).css("width","93px");
  });
 }
}
/////////////
// ONLOAD //
////////////
$(document).ready(function()
{
 fixIESelect();
});

For my layout, I didn't want a hack (no width increasing, no on click with auto and then coming to original). It broke my existing layout. I just wanted it to work normally like other browsers.

I found this to be exactly like that :-

http://www.jquerybyexample.net/2012/05/fix-for-ie-select-dropdown-with-fixed.html


A workaround if you don't care about the strange view after an option is selected (i.e. Select to jump to a new page):

<!-- Limit width of the wrapping div instead of the select and use 'overflow: hidden' to hide the right part of it. -->
<div style='width: 145px; overflow: hidden; border-right: 1px solid #aaa;'>
  <select onchange='jump();'>
    <!-- '&#9660;(▼)' produces a fake dropdown indicator -->
    <option value=''>Jump to ... &#9660;</option>
    <option value='1'>http://stackoverflow.com/questions/682764/select-dropdown-with-fixed-width-cutting-off-content-in-ie</option>
    ...
  </select>
</div>

A pure css solution : http://bavotasan.com/2011/style-select-box-using-only-css/

.styled-select select {
   background: transparent;
   width: 268px;
   padding: 5px;
   font-size: 16px;
   line-height: 1;
   border: 0;
   border-radius: 0;
   height: 34px;
   -webkit-appearance: none;
   }

.styled-select {
   width: 240px;
   height: 34px;
   overflow: hidden;
   background: url(http://cdn.bavotasan.com/wp-content/uploads/2011/05/down_arrow_select.jpg) no-repeat right #ddd;
   border: 1px solid #ccc;
   }
<div class="styled-select">
   <select>
      <option>Here is the first option</option>
      <option>The second option</option>
   </select>
</div>


Best solution: css + javascript

http://css-tricks.com/select-cuts-off-options-in-ie-fix/

var el;

$("select")
  .each(function() {
    el = $(this);
    el.data("origWidth", el.outerWidth()) // IE 8 can haz padding
  })
  .mouseenter(function(){
    $(this).css("width", "auto");
  })
  .bind("blur change", function(){
    el = $(this);
    el.css("width", el.data("origWidth"));
  });

ReferenceURL : https://stackoverflow.com/questions/682764/select-dropdown-with-fixed-width-cutting-off-content-in-ie

반응형