2016-03-22 2 views
0

У меня есть styled-select, который я сделал для своих требований. Теперь проблема заключается в том, что если выбран вариант больше всей площади, естественно, она заполнит весь div, как показано на рисунке ниже:Ограничьте текст в div, но сделайте весь div щелчком мыши

enter image description here

Теперь я хочу, чтобы это было ограничено или иметь запас справа, чтобы показать стрелку, который я использовал в качестве background: url, как на картинке ниже:

enter image description here

Если я уменьшить ширину div это будет хорошо, но проблема в том, что он выиграл 'clickable i n, чтобы открыть раскрывающееся меню. Теперь я хочу знать, есть ли решение ограничить текст, но все же есть область с кликами?

Вот мой код: Working jsFiddle

$(function() { 
 

 
    $('.styled-select select').hide(); 
 
    $("select#elem").val('0'); 
 

 
    $('.styled-select div').each(function() { 
 
    var $container = $(this).closest('.styled-select'); 
 
    $(this).html($container.find('select option:selected').text()); 
 
    }); 
 

 
    $('.styled-select div').click(function() { 
 
    var $container = $(this).closest('.styled-select'); 
 
    var opLen = $container.find('select').children('option').length; 
 
    if (opLen < 5) { 
 
     $container.find('select').show().attr('size', opLen).focus(); 
 
    } else { 
 
     $container.find('select').show().attr('size', 5).focus(); 
 
    } 
 
    }); 
 

 
    $('.styled-select select').click(function() { 
 
    var $container = $(this).closest('.styled-select'); 
 
    var text = $container.find('select option:selected').text(); 
 
    $container.find('div').html(text); 
 
    $container.find('select').hide(); 
 
    }); 
 

 
    $('.styled-select select').focusout(function() { 
 
    var $container = $(this).closest('.styled-select'); 
 
    $container.find('select').hide(); 
 
    }); 
 

 
});
.styled-select select { 
 
\t position: absolute; 
 
\t background: transparent; 
 
\t width: 420px; 
 
\t padding-top: 5px; 
 
\t font-size: 18px; 
 
\t font-family: 'PT Sans', sans-serif; 
 
\t color: black; 
 
\t border: 0; 
 
\t border-radius: 4; 
 
\t -webkit-appearance: none; 
 
\t -moz-appearance: none; 
 
\t -o-appearance: none; 
 
\t z-index: 1; 
 
\t outline: none; 
 
\t top: 42px; 
 
\t box-shadow: 0 2px 2px 0 #C2C2C2; 
 
\t } 
 
\t 
 
\t .styled-select { 
 
\t background: url('http://s22.postimg.org/f5gjjtswd/campaign_Selector.png') no-repeat right; 
 
\t background-color: white; 
 
\t width: 420px; 
 
\t height: 42px; 
 
\t position: relative; 
 
\t margin: 0 auto; 
 
\t box-shadow: 0 2px 2px 0 #C2C2C2; 
 
\t background-position: 97% 50%; 
 
\t } 
 
\t 
 
\t .styled-select option { 
 
\t font-size: 18px; 
 
\t background-color: white; 
 
\t margin-left: 3px; 
 
\t }
<div class="styled-select" style="width: 301px; margin:5px 0 0 10px;"> 
 
    <script src="https://code.jquery.com/jquery-1.9.1.js"></script> 
 
    <script src="https://code.jquery.com/ui/1.10.2/jquery-ui.js"></script> 
 
    <div id="userChannelDivId" style="font-size:18px; position: absolute; top: 8px; left: 5px; width: 295px; height: 42px; white-space:nowrap; overflow:hidden"></div> 
 
    <select id="userChannelId" name="userChannelId" style="width:100%"> 
 
    <option value="">resh resh reshadreshadreshadreshadreshad resh</option> 
 
    <option value="">--- Select ---</option> 
 
    <option value="">--- Celect ---</option> 
 
    <option value="">--- Delect ---</option> 
 
    <option value="">--- Felect ---</option> 
 
    <option value="">--- Gelect ---</option> 
 
    </select> 
 
</div>

+1

Было бы лучше, если бы вы выложили ** нерабочим ** код, чтобы мы могли видеть, что вы сделали неправильно, и нужно исправить. – Barmar

+0

@Barmar рабочий код работает не так, как ожидалось.Мое ожидаемое поведение - это тот, у кого ограниченная текстовая область – reshad

+1

Вам лучше разместить более релевантную картину ожидаемого поведения, потому что белая стрелка на белом фоне не имеет большого смысла ... –

ответ

3

изменение в #UserChannelDivID ...

width: 265px; 
text-overflow: ellipsis; 
padding: 0 30px 0 0; 

Fiddle

1

Вы можете изменить размер div, а затем применить прозрачную границу, которая позволит расширить емкость над клещом.

Как таковой:

#userChannelDivId { 
    width: 250px !important; 
    border-right: 45px solid transparent; 
} 

делает трюк.

https://jsfiddle.net/qyf22h83/13/

+0

Отлично! это прекрасно работает. Через 3 минуты я выберу его как правильный ответ. Спасибо;) – reshad

+1

Большое спасибо за вашу помощь. Ответ @Scott был немного лучше. снова спасибо большое – reshad

+0

IMO это уродливый, не смысловой хак. –

-1

Вот яваскрипт альтернативы, используя подстроку, которая также добавляемое многоточие (3 ...) в укажите, что это значение больше, чем отображается. Вы можете изменить диапазон до того, что вам нравится, я просто установил его на 20 символов.

$('.styled-select div').each(function() { 
     var $container = $(this).closest('.styled-select'); 
     var value = $container.find('select option:selected').text(); 
     value = value.substring(0, 20) + '...'; 
     $(this).html(value); 
    }); 
+0

Помощник Downvoter, чтобы поделиться, почему? OP уже работает в Javascript, чтобы даже заполнить его поле. Почему бы просто не позаботиться об этом при заполнении поля вместо использования хакерского CSS для выполнения того же самого? edit: на самом деле ответ Скотта довольно хорош по сравнению с другими:] – sm1215

0

Только CSS Решение

на основе select-css Github репо, вот CSS-единственное решение. Нет необходимости в причудливом JavaScript, когда тег HTML select обеспечивает все функциональные возможности. Это решение заменяет раскрывающуюся стрелку. Wrap выберите в custom-select div и добавьте CSS. Замените определение стрелки раскрывающегося списка на свой собственный.

https://jsfiddle.net/sacwebdeveloper/ctchr3ph/

/* Container used for styling the custom select, the buttom class below adds the 
 
* bg gradient, corners, etc. */ 
 
.custom-select { 
 
\t position: relative; 
 
\t display: block; 
 
} 
 

 
/* This is the native select, we're making everything but the text invisible so 
 
* we can see the button styles in the wrapper */ 
 
.custom-select select { 
 
\t width: 100%; 
 
\t margin: 0; 
 
\t outline: none; 
 
\t padding: .6em .8em .5em .8em; 
 
    
 
\t /* Prefixed box-sizing rules necessary for older browsers */ 
 
\t -webkit-box-sizing: border-box; 
 
\t -moz-box-sizing: border-box; 
 
\t box-sizing: border-box; 
 

 
\t /* Font size must be 16px to prevent iOS page zoom on focus */ 
 
\t font-size: 16px; 
 
} 
 

 

 
/* Custom arrow sits on top of the select - could be an image, SVG, icon font, 
 
* etc. or the arrow could just baked into the bg image on the select. */ 
 
.custom-select::after { 
 
\t content: " "; 
 
\t position: absolute; 
 
\t top: 50%; 
 
\t right: 1em; 
 
\t z-index: 2; 
 
\t /* These hacks make the select behind the arrow clickable in some browsers */ 
 
\t pointer-events: none; 
 
\t display: none; 
 
} 
 

 
.custom-select::after { 
 
    width: 0; 
 
    height: 0; 
 
    border-left: 4px solid transparent; 
 
    border-right: 4px solid transparent; 
 
    border-top: 7px solid #666; 
 
    margin-top: -3px; 
 
} 
 

 
@supports (-webkit-appearance: none) or (appearance: none) 
 
\t /* Firefox <= 34 has a false positive on @supports(-moz-appearance: none) 
 
\t * @supports (mask-type: alpha) is Firefox 35+ 
 
\t */ 
 
\t or ((-moz-appearance: none) and (mask-type: alpha)) { 
 
\t 
 
\t /* Show custom arrow */ 
 
\t .custom-select::after { 
 
\t \t display: block; 
 
\t } 
 

 
\t /* Remove select styling */ 
 
\t .custom-select select { 
 
\t \t padding-right: 2em; /* Match-01 */ 
 
\t \t /* inside @supports so that iOS <= 8 display the native arrow */ 
 
\t \t background: none; /* Match-04 */ 
 
\t \t /* inside @supports so that Android <= 4.3 display the native arrow */ 
 
\t \t border: 1px solid transparent; /* Match-05 */ 
 

 
\t \t -webkit-appearance: none; 
 
\t \t -moz-appearance: none; 
 
\t \t appearance: none; 
 
\t } 
 
\t .custom-select select:focus { 
 
\t \t border-color: #aaa; /* Match-03 */ 
 
\t } 
 
} 
 

 
.custom-select { 
 
    background-color: white; 
 
    margin-top: 40px; 
 
}
<div class="custom-select"> 
 
    <select id="userChannelId" name="userChannelId"> 
 
    <option value="">resh resh reshadreshadreshadreshadreshad resh</option> 
 
    <option value="">--- Select ---</option> 
 
    <option value="">--- Celect ---</option> 
 
    <option value="">--- Delect ---</option> 
 
    <option value="">--- Felect ---</option> 
 
    <option value="">--- Gelect ---</option> 
 
    </select> 
 
</div>

+0

Обратите внимание, что это * не * стиль списка опций в любом случае, оставляя это для стиля браузера по умолчанию. Я не думаю, что это то, что здесь нужно. – Scott

+0

Вы можете легко создать тег опции с помощью CSS. Я просто попытался, и мне удалось изменить размер шрифта, цвет фона и т. Д. На самом деле, OP сделал то же самое, они использовали список опций и ввели его в стиле. – SacWebDeveloper

Смежные вопросы