문제

IE에서 드롭다운 목록은 드롭박스와 동일한 너비를 사용하는 반면(이해가 되기를 바랍니다) Firefox에서는 드롭다운 목록의 너비가 콘텐츠에 따라 다릅니다.

이는 기본적으로 드롭박스가 가능한 가장 긴 선택 항목을 표시할 수 있을 만큼 충분히 넓은지 확인해야 함을 의미합니다.이로 인해 내 페이지가 매우 보기 흉해 보입니다. :(

이 문제에 대한 해결 방법이 있습니까?CSS를 사용하여 드롭박스와 드롭다운 목록의 너비를 다르게 설정하려면 어떻게 해야 하나요?

도움이 되었습니까?

해결책

여기 또 있어요 jQuery 기반 예시.여기에 게시된 다른 모든 답변과 달리 모든 키보드 및 마우스 이벤트, 특히 클릭이 고려됩니다.

if (!$.support.leadingWhitespace) { // if IE6/7/8
    $('select.wide')
        .bind('focus mouseover', function() { $(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'); });
}

다음 CSS와 함께 사용하세요.

select {
    width: 150px; /* Or whatever width you want. */
}
select.expand {
    width: auto;
}

당신이해야 할 일은 클래스를 추가하는 것뿐입니다 wide 문제의 드롭다운 요소에 추가합니다.

<select class="wide">
    ...
</select>

다음은 jsfiddle 예제입니다..도움이 되었기를 바랍니다.

다른 팁

자신만의 드롭다운 목록을 만드는 것은 그만한 가치가 있는 것보다 더 고통스럽습니다.일부 JavaScript를 사용하여 IE 드롭다운이 작동하도록 할 수 있습니다.

IE 선택 상자를 수정하기 위해 약간의 YUI 라이브러리와 특수 확장을 사용합니다.

다음 사항을 포함하고 포장해야 합니다. <select> 요소 <span class="select-box">

페이지의 body 태그 앞에 다음을 입력하세요.

<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/yahoo_2.0.0-b3.js" type="text/javascript">
</script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/event_2.0.0-b3.js" type="text/javascript">
</script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/dom_2.0.2-b3.js" type="text/javascript">
</script>
<script src="ie-select-width-fix.js" type="text/javascript">
</script>
<script>
// for each select box you want to affect, apply this:
var s1 = new YAHOO.Hack.FixIESelectWidth( 's1' ); // s1 is the ID of the select box you want to affect
</script>

게시물 승인 편집:

YUI 라이브러리와 Hack 컨트롤 없이도 이 작업을 수행할 수 있습니다.실제로 해야 할 일은 선택 요소에 onmouseover="this.style.width='auto'" onmouseout="this.style.width='100px'" (또는 원하는 대로)를 추가하는 것입니다.YUI 컨트롤은 멋진 애니메이션을 제공하지만 꼭 필요한 것은 아닙니다.이 작업은 jquery 및 기타 라이브러리로도 수행할 수 있습니다(물론 이에 대한 명시적인 문서는 찾지 못했습니다).

-- 편집 내용 수정:
IE는 선택 컨트롤에 대한 onmouseout에 문제가 있습니다(옵션에 마우스를 올리면 선택에 마우스를 올려놓는 것을 고려하지 않습니다).이로 인해 마우스아웃을 사용하는 것이 매우 까다로워졌습니다.첫 번째 솔루션은 지금까지 찾은 것 중 최고입니다.

다음을 시도해 볼 수 있습니다 ...

  styleClass="someStyleWidth"
  onmousedown="javascript:if(navigator.appName=='Microsoft Internet Explorer'){this.style.position='absolute';this.style.width='auto'}" 
  onblur="this.style.position='';this.style.width=''"

나는 시도했고 그것은 나에게 효과적입니다.다른 것은 필요하지 않습니다.

다음 솔루션을 사용했는데 대부분의 상황에서 잘 작동하는 것 같습니다.

<style>
select{width:100px}
</style>

<html>
<select onmousedown="if($.browser.msie){this.style.position='absolute';this.style.width='auto'}" onblur="this.style.position='';this.style.width=''">
  <option>One</option>
  <option>Two - A long option that gets cut off in IE</option>
</select>
</html>

메모:그만큼 $.browser.msie jquery가 필요합니다.

@흐림 이벤트 핸들러도 추가해야 합니다

$(document).ready(function(){
    $("#dropdown").mousedown(function(){
        if($.browser.msie) {
            $(this).css("width","auto");
        }
    });
    $("#dropdown").change(function(){
        if ($.browser.msie) {
            $(this).css("width","175px");
        }
    });
    $("#dropdown").blur(function(){
        if ($.browser.msie) {
            $(this).css("width","175px");
        }
    });
});

그러나 클릭하면 요소 대신 선택 상자가 계속 확장됩니다.(IE6에서는 실패하는 것 같지만 Chrome과 IE7에서는 완벽하게 작동합니다)

IE6/IE7/IE8에서는 이를 수행할 방법이 없습니다.컨트롤은 앱에 의해 그려지지만 IE는 그런 식으로 그리지 않습니다.가장 좋은 방법은 드롭다운의 너비와 목록의 너비가 다른 것이 중요하다면 간단한 HTML/CSS/JavaScript를 통해 자신만의 드롭다운을 구현하는 것입니다.

jQuery를 사용하는 경우 다음 IE 선택 너비 플러그인을 사용해 보세요.

http://www.jainaewen.com/files/javascript/jquery/ie-select-style/

이 플러그인을 적용하면 고정 너비의 모양과 스타일을 잃지 않고 옵션 요소가 전체 너비로 열리도록 허용하여 Internet Explorer의 선택 상자가 Firefox, Opera 등에서 작동하는 것처럼 작동하는 것처럼 보입니다.또한 Internet Explorer 6 및 7의 선택 상자에 패딩 및 테두리에 대한 지원이 추가되었습니다.

jQuery에서는 이것이 꽤 잘 작동합니다.드롭다운에 id="dropdown"이 있다고 가정합니다.

$(document).ready(function(){

    $("#dropdown").mousedown(function(){
    if($.browser.msie) {
        $(this).css("width","auto");
    }
    });
    $("#dropdown").change(function(){
    if ($.browser.msie) {
        $(this).css("width","175px");
    }
    });

});

가장 간단한 해결책은 다음과 같습니다.

시작하기 전에 IE6을 제외한 거의 모든 브라우저에서 드롭다운 선택 상자가 자동으로 확장된다는 점을 알려드립니다.따라서 브라우저 검사(예: IE6)를 수행하고 해당 브라우저에만 다음을 작성합니다.여기 간다.먼저 브라우저를 확인하세요.

코드는 드롭다운 선택 상자를 마법처럼 확장합니다.이 솔루션의 유일한 문제는 마우스를 올리면 드롭다운이 420px로 확장되고 오버플로 = 숨겨지기 때문에 확장된 드롭다운 크기를 숨기고 170px로 표시한다는 것입니다.따라서 ddl 오른쪽에 있는 화살표가 숨겨져 보이지 않게 됩니다.하지만 선택 상자는 420px로 확장됩니다.그것이 우리가 정말로 원하는 것입니다.아래 코드를 직접 시도해보고 마음에 들면 사용하세요.

.ctrDropDown
{
    width:420px; <%--this is the actual width of the dropdown list--%>
}
.ctrDropDownClick
{
    width:420px; <%-- this the width of the dropdown select box.--%>
}

<div style="width:170px; overflow:hidden;">
<asp:DropDownList runat="server" ID="ddlApplication" onmouseout = "this.className='ctrDropDown';" onmouseover ="this.className='ctrDropDownClick';" class="ctrDropDown" onBlur="this.className='ctrDropDown';" onMouseDown="this.className='ctrDropDownClick';" onChange="this.className='ctrDropDown';"></asp:DropDownList>
</div>

위의 내용은 IE6 CSS입니다.다른 모든 브라우저의 공통 CSS는 다음과 같습니다.

.ctrDropDown
{
    width:170px; <%--this is the actual width of the dropdown list--%>
}
.ctrDropDownClick
{
    width:auto; <%-- this the width of the dropdown select box.--%>
}

전환 효과가 없는 간단한 드롭다운 및/또는 플라이아웃 메뉴를 원한다면 CSS를 사용하세요.조건부 첨부 CSS 파일에 정의된 동작(IE6 전용 속성)과 함께 .htc 파일(css3hover?)을 사용하여 모든 요소에 대해 IE6에서 :hover를 지원하도록 강제할 수 있습니다.

이것 좀 봐..완벽하지는 않지만 작동하며 IE 전용이며 FF에는 영향을 미치지 않습니다.IE 전용 수정을 설정하기 위해 onmousedown에 일반 자바스크립트를 사용했습니다.하지만 jquery의 msie는 onmousedown에서도 사용할 수 있습니다.주요 아이디어는 "onchange"이고 선택 상자가 정상으로 돌아가도록 하는 흐림 효과입니다.당신이 그 너비를 결정합니다.35%가 필요했어요.

onmousedown="javascript:if(navigator.appName=='Microsoft Internet Explorer'){this.style.width='auto'}" 
onchange="this.style.width='35%'"
onblur="this.style.width='35%'"

위의 BalusC 답변은 훌륭하지만 드롭다운 콘텐츠의 너비가 CSS select.expand에서 정의한 것보다 작은 경우 추가할 작은 수정 사항이 있습니다. 이것을 마우스오버 바인드에 추가하세요.

.bind('mouseover', function() { $(this).addClass('expand').removeClass('clicked');
                                if ($(this).width() < 300) // put your desired minwidth here
                                {
                                    $(this).removeClass('expand');
                                }})

이것은 내가 다른 사람의 물건을 조금 가져간 일입니다.

        $(document).ready(function () {
        if (document.all) {

            $('#<%=cboDisability.ClientID %>').mousedown(function () {
                $('#<%=cboDisability.ClientID %>').css({ 'width': 'auto' });
            });

            $('#<%=cboDisability.ClientID %>').blur(function () {
                $(this).css({ 'width': '208px' });
            });

            $('#<%=cboDisability.ClientID %>').change(function () {
                $('#<%=cboDisability.ClientID %>').css({ 'width': '208px' });
            });

            $('#<%=cboEthnicity.ClientID %>').mousedown(function () {
                $('#<%=cboEthnicity.ClientID %>').css({ 'width': 'auto' });
            });

            $('#<%=cboEthnicity.ClientID %>').blur(function () {
                $(this).css({ 'width': '208px' });
            });

            $('#<%=cboEthnicity.ClientID %>').change(function () {
                $('#<%=cboEthnicity.ClientID %>').css({ 'width': '208px' });
            });

        }
    });

여기서 cboEthnicity 및 cboDisability는 선택 자체의 너비보다 넓은 옵션 텍스트가 있는 드롭다운입니다.

보시다시피 IE에서만 작동하는 document.all을 지정했습니다.또한 다음과 같이 div 요소 내에 드롭다운을 포함했습니다.

<div id="dvEthnicity" style="width: 208px; overflow: hidden; position: relative; float: right;"><asp:DropDownList CssClass="select" ID="cboEthnicity" runat="server" DataTextField="description" DataValueField="id" Width="200px"></asp:DropDownList></div>

이는 드롭다운이 확장될 때 다른 요소가 제자리에서 벗어나는 것을 처리합니다.여기서 유일한 단점은 선택할 때 메뉴 목록 시각적 개체가 사라지지만 선택하자마자 다시 돌아온다는 것입니다.

이것이 누군가에게 도움이 되기를 바랍니다.

이것이 가장 좋은 방법입니다:

select:focus{
    min-width:165px;
    width:auto;
    z-index:9999999999;
    position:absolute;
}

BalusC 솔루션과 똑같습니다.이것만이 더 쉽습니다.;)

완전한 기능을 갖춘 jQuery 플러그인을 사용할 수 있습니다.깨지지 않는 레이아웃과 키보드 상호 작용을 지원합니다. 데모 페이지를 확인하세요. http://powerkiki.github.com/ie_expand_select_width/

부인 성명:내가 코딩했는데, 패치 환영

jquery BalusC의 솔루션이 개선되었습니다.또한 사용:브래드 로버트슨의 여기에 댓글을 달다.

이것을 .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');
    })
    }
}

선택 요소에 직접 스타일을 추가할 수 있습니다.

<select name="foo" style="width: 200px">

따라서 이 선택 항목의 너비는 200픽셀이 됩니다.

또는 요소에 클래스나 ID를 적용하고 스타일시트에서 참조할 수 있습니다.

지금까지는 하나도 없습니다.IE8에 대해서는 모르지만 자바스크립트로 자체 드롭다운 목록 기능을 구현하지 않는 한 IE6 및 IE7에서는 수행할 수 없습니다.웹에 이를 수행하는 방법에 대한 예가 있지만 기존 기능을 복제하는 데에는 큰 이점이 없습니다.

asp:dropdownlist에도 같은 내용이 있습니다.

Firefox(3.0.5)에서 드롭다운은 드롭다운에서 가장 긴 항목의 너비로, 너비는 600픽셀 정도입니다.

이것은 IE6에서 작동하는 것으로 보이며 다른 것들은 손상되지 않는 것 같습니다.또 다른 좋은 점은 드롭다운 선택 항목을 변경하자마자 메뉴가 자동으로 변경된다는 것입니다.

$(document).ready(function(){
    $("#dropdown").mouseover(function(){
        if($.browser.msie) {
            $(this).css("width","auto");
        }
    });
    $("#dropdown").change(function(){
        if ($.browser.msie) {
            $("#dropdown").trigger("mouseover");
        }
    });

});

첫 번째 모범 답변의 hedgerwow 링크(YUI 애니메이션 해결 방법)가 끊어졌습니다. 도메인이 만료된 것 같습니다.코드가 만료되기 전에 복사했으므로 여기에서 찾을 수 있습니다. (코드 소유자는 저작권을 위반하는 경우 코드를 다시 업로드하여 알려줄 수 있습니다.)

http://ciitronian.com/blog/programming/yui-button-mimicking-native-select-dropdown-avoid-width-problem/

같은 블로그 게시물에서 YUI 버튼 메뉴를 사용하여 일반 요소와 똑같은 SELECT 요소를 만드는 방법에 대해 썼습니다.살펴보고 이것이 도움이 되는지 알려주세요!

게시 한 솔루션을 기반으로 사이, 이것이 jQuery를 사용하여 수행하는 방법입니다.

$(document).ready(function() {
    if ($.browser.msie) $('select.wide')
        .bind('onmousedown', function() { $(this).css({position:'absolute',width:'auto'}); })
        .bind('blur', function() { $(this).css({position:'static',width:''}); });
});

나는 내 모자를 링에 던질 것이라고 생각했습니다.SaaS 애플리케이션을 만들고 테이블 안에 선택 메뉴가 포함되어 있습니다.이 방법은 효과가 있었지만 테이블의 모든 내용이 왜곡되었습니다.

onmousedown="if(navigator.appName=='Microsoft Internet Explorer'){this.style.position='absolute';this.style.width='auto'}
onblur="if(navigator.appName=='Microsoft Internet Explorer'){this.style.position=''; this.style.width= '225px';}"

그래서 모든 것을 더 좋게 만들기 위해 제가 한 일은 Z-인덱스 div 안에 선택 항목을 던지는 것이었습니다.

<td valign="top" style="width:225px; overflow:hidden;">
    <div style="position: absolute; z-index: 5;" onmousedown="var select = document.getElementById('select'); if(navigator.appName=='Microsoft Internet Explorer'){select.style.position='absolute';select.style.width='auto'}">
        <select name="select_name" id="select" style="width: 225px;" onblur="if(navigator.appName=='Microsoft Internet Explorer'){this.style.position=''; this.style.width= '225px';}" onChange="reportFormValues('filter_<?=$job_id?>','form_values')">
            <option value="0">All</option>
            <!--More Options-->
        </select>
    </div>
</td>

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 코드

<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>

나는 이 문제를 해결해야 했고 IE6, 7, 8에서 작동하는(물론 다른 브라우저와도 호환되는) 매우 완벽하고 확장 가능한 솔루션을 생각해냈습니다.나는 여기에 관한 전체 기사를 썼습니다. http://www.edgeoftheworld.fr/wp/work/dealing-with-fixed-size-dropdown-lists-in-internet-explorer

위의 해결 방법 중 어느 것도 모든 경우에 작동하지 않기 때문에(제 생각에는) 여전히 이 문제에 직면한 사람들을 위해 이 내용을 공유하고 싶습니다.

나는 이러한 모든 솔루션을 시도했지만 나에게 완전히 효과가 있는 솔루션은 없었습니다.이것이 내가 생각해낸 것이다

$(document).ready(function () {

var clicknum = 0;

$('.dropdown').click(
        function() {
            clicknum++;
            if (clicknum == 2) {
                clicknum = 0;
                $(this).css('position', '');
                $(this).css('width', '');
            }
        }).blur(
        function() {
            $(this).css('position', '');
            $(this).css('width', '');
            clicknum = 0;
        }).focus(
        function() {
            $(this).css('position', 'relative');
            $(this).css('width', 'auto');
        }).mousedown(
        function() {
            $(this).css('position', 'relative');
            $(this).css('width', 'auto');
        });
})(jQuery);

HTML의 각 드롭다운에 드롭다운 클래스를 추가해야 합니다.

여기서의 비결은 특수한 클릭 기능을 사용하는 것입니다(여기에서 찾았습니다). jQuery를 사용하여 DropDownList 항목을 선택할 때마다 이벤트 발생).여기에 있는 다른 많은 솔루션은 잘 작동하지만 사용자가 이전에 선택한 것과 동일한 옵션을 선택하면 트리거되지 않는 이벤트 핸들러 변경을 사용합니다.

다른 많은 솔루션과 마찬가지로 focus 및 mousedown은 사용자가 드롭다운에 초점을 맞출 때 사용되며, 흐림은 클릭할 때 사용됩니다.

여기에 일종의 브라우저 감지 기능을 추가하여 효과만 있을 수도 있습니다.다른 브라우저에서는 나쁘지 않아 보이지만

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top