IE의 드롭 다운 목록 너비
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 드롭 다운이 작동하도록 할 수 있습니다.
약간의 YUI 라이브러리와 IE 선택 상자를 수정하기위한 특수 확장을 사용합니다.
다음을 포함하고 <select>
요소를<span class="select-box">
페이지의 본문 태그 앞에 다음을 넣으십시오.
<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 컨트롤 없이도이 작업을 수행 할 수 있습니다. 정말 필요한 것은 select 요소에 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가 필요합니다.
@Thad 당신은 또한 흐림 이벤트 핸들러를 추가해야합니다
$(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)를 수행하고 해당 브라우저에만 다음을 작성합니다. 여기 간다. 먼저 브라우저를 확인하십시오.
이 코드는 드롭 다운 선택 상자를 마술처럼 확장합니다. 솔루션의 유일한 문제는 onmouseover 드롭 다운이 420px로 확장되며 overflow = hidden이기 때문에 확장 된 드롭 다운 크기를 숨기고 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를 사용하십시오. IE6에서 .htc 파일 (css3hover?)을 사용하여 모든 요소에서 : hover를 지원하도록 강제 할 수 있습니다 (IE6 전용 속성). 조건부로 첨부 된 CSS 파일
이것을 확인하십시오 .. 완벽하지는 않지만 작동하며 IE 전용이며 FF에 영향을 미치지 않습니다. 나는 onmousedown에 대한 일반 자바 스크립트를 사용하여 IE 전용 수정 사항을 설정했습니다.하지만 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/
면책 조항 : 나는 그것을 코딩했다, 패치 환영
http://developer.yahoo.com/yui/examples/button/button-menu-select.html#
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');
})
}
}
선택 요소에 직접 스타일을 추가 할 수 있습니다.
<select name="foo" style="width: 200px">
따라서이 선택 항목의 너비는 200 픽셀이됩니다.
또는 클래스 또는 ID를 요소에 적용하고 스타일 시트에서 참조 할 수 있습니다.
So far there isn't one. Don't know about IE8 but it cannot be done in IE6 & IE7, unless you implement your own dropdown list functionality with javascript. There are examples how to do it on the web, though I don't see much benefit in duplicating existing functionality.
We have the same thing on an asp:dropdownlist:
In Firefox(3.0.5) the dropdown is the width of the longest item in the dropdown, which is like 600 pixels wide or something like that.
This seems to work with IE6 and doesn't appear to break others. The other nice thing is that it changes the menu automatically as soon as you change your drop down selection.
$(document).ready(function(){
$("#dropdown").mouseover(function(){
if($.browser.msie) {
$(this).css("width","auto");
}
});
$("#dropdown").change(function(){
if ($.browser.msie) {
$("#dropdown").trigger("mouseover");
}
});
});
The hedgerwow link (the YUI animation work-around) in the first best answer is broken, I guess the domain got expired. I copied the code before it got expired, so you can find it here (owner of code can let me know if I am breaching any copyrights by uploading it again)
On the same blog post I wrote about making an exact same SELECT element like the normal one using YUI Button menu. Have a look and let me know if this helps!
Based on the solution posted by Sai, this is how to do it with 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:''}); });
});
I thought I'd throw my hat in the ring. I make a SaaS application and I had a select menu embedded inside a table. This method worked, but it skewed everything in the table.
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';}"
So what I did to make it all better was throw the select inside a z-indexed 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>
Its tested in all version of IE, Chrome, FF & Safari
// JavaScript code
<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>
I've had to work around this issue and once came up with a pretty complete and scalable solution working for IE6, 7 and 8 (and compatible with other browsers obviously). I've written a whole article about it right here: http://www.edgeoftheworld.fr/wp/work/dealing-with-fixed-sized-dropdown-lists-in-internet-explorer
Thought I'd share this for people who are still running into this problem, as none of the above solutions work in every case (in my opinion).
I tried all of these solutions and none worked completely for me. This is what I came up with
$(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);
Be sure to add a dropdown class to each dropdown in your html
The trick here is using the specialized click function (I found it here Fire event each time a DropDownList item is selected with jQuery). Many of the other solutions on here use the event handler change, which works well but won't trigger if the user selects the same option as was previously selected.
Like many of the other solutions, focus and mousedown is for when the user puts the dropdown in focus, blur is for when they click away.
You may also want to stick some kind of browser detection in this so it only effects ie. It doesn't look bad in other browsers though
참고URL : https://stackoverflow.com/questions/73960/dropdownlist-width-in-ie
'program story' 카테고리의 다른 글
열의 값을 R의 기존 데이터 프레임에있는 행 이름으로 변환 (0) | 2020.09.01 |
---|---|
Google+ 담벼락에 게시하는 방법 (0) | 2020.09.01 |
Clojure 개발자가 피해야 할 일반적인 프로그래밍 실수 (0) | 2020.09.01 |
Maven이 컴파일하고 빌드 jar에 포함 할 추가 소스 디렉토리를 추가하는 방법은 무엇입니까? (0) | 2020.09.01 |
사용자가 언어를 선택할 때 앱의 언어를 변경하는 방법은 무엇입니까? (0) | 2020.09.01 |