1

Есть вот такой выпадающий список.

select {
  width: 180px;
  padding: 3px 5px;
  height: 25px;
  line-height: 25px;
  background: transparent;
  border: none;
  cursor: pointer;
}

div {
  width: 150px;
  height: 25px;
  overflow: hidden;
  background-color: #ebebeb;
  background-image: url(http://cdn.joxi.ru/media/cache/preview/uploads/prod/2014/05/13/f8e/b5f/e82b8e0d4ed7fe4b8eaef79b94cff9022da760a7.jpg) no-repeat right center;
  background: url(http://cdn.joxi.ru/media/cache/preview/uploads/prod/2014/05/13/f8e/b5f/e82b8e0d4ed7fe4b8eaef79b94cff9022da760a7.jpg) no-repeat right center, -webkit-linear-gradient(bottom, #dbdbdb, #fafafa);
  background: url(http://cdn.joxi.ru/media/cache/preview/uploads/prod/2014/05/13/f8e/b5f/e82b8e0d4ed7fe4b8eaef79b94cff9022da760a7.jpg) no-repeat right center, -moz-linear-gradient(bottom, #dbdbdb, #fafafa);
  background: url(http://cdn.joxi.ru/media/cache/preview/uploads/prod/2014/05/13/f8e/b5f/e82b8e0d4ed7fe4b8eaef79b94cff9022da760a7.jpg) no-repeat right center, -ms-linear-gradient(bottom, #dbdbdb, #fafafa);
  background: url(http://cdn.joxi.ru/media/cache/preview/uploads/prod/2014/05/13/f8e/b5f/e82b8e0d4ed7fe4b8eaef79b94cff9022da760a7.jpg) no-repeat right center, -o-linear-gradient(bottom, #dbdbdb, #fafafa);
  background: url(http://cdn.joxi.ru/media/cache/preview/uploads/prod/2014/05/13/f8e/b5f/e82b8e0d4ed7fe4b8eaef79b94cff9022da760a7.jpg) no-repeat right center, linear-gradient(bottom, #dbdbdb, #fafafa);
  border: 1px solid #797a7c;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}
<div>
  <select>
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
  </select>
</div>

Пример на jsfiddle

Вопросы:

  1. Как сделать, чтобы ширина опций была равна ширине стилизованного селекта?
  2. Как убрать обводку вокруг всех опций?

Хотелось бы решить данные вопросы на чистом CSS, либо с минимальным внедрением JavaScript (jQuery).

2
  • К сожалению не поддаются CSS селекты) По ссылке статья, там как раз об этом и вариант решения проблемы. dimox.name/styling-select-boxes-using-jquery-css Использование плагинов jquery допустимо?
    – iterq
    13 мая 2014 в 9:26
  • Вообще, конечно, желательно все это решить без сторонних плагинов. По сути, возникает только эти 2 проблемы, со стилизацией каждой отдельной опции проблем не будет.
    – andreyqin
    13 мая 2014 в 9:31

2 ответа 2

1

Вот пример: http://jsfiddle.net/8vFLy/3/

$("#current_option").click(function(){
    customOptionsBlock = $("#custom_options");
    if (customOptionsBlock.is(":hidden")) {
        $("#custom_options").show();
    }
    else {
        $("#custom_options").hide();
    }
});

$("#custom_options li").click(function(){
    choosenValue = $(this).attr("data-value");
    $("select").val(choosenValue).prop("selected", true);
    $("#current_option span").text($(this).text());
    $("#current_option").attr("data-value", choosenValue);
});
#custom_select {
    width: 100px;
    text-align: center;
}

#current_option {
    width: 100%;
    background: #d2d2d2;
    border: 1px solid grey;
    line-height: 25px;
    cursor: pointer;
    border-radius: 4px;
}

#current_option:hover {
    background: #EBEBEB;
}

#current_option b{
    height: 100%;
    width: 20px;
    float: right;
    border-left: 1px solid grey;
}

#current_option b img{
    width: 10px;
    height: 10px;
    margin-top: 5px;
}

#custom_options {
    display: none;
    width: 100%;
    padding: 0;
    margin-top: -2px;
    background: #EBEBEB;
    border: 1px solid grey;
    border-radius: 0 0 4px 4px;
}

#custom_options li {
    list-style: none;
    padding: 0;
    width: 100%;
    height: 25px;
    text-align: center;
}

#custom_options li:last-child {
    border-radius: 0 0 4px 4px;
}

#custom_options li:first-child {
    margin-top: 4px;
}

#custom_options li:hover{
    background: #d2d2d2;
    cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<select>
    <option value="">--------</option>
    <option value="1">Opt1</option>
    <option value="2">Opt2</option>
    <option value="3">Opt3</option>
</select>

<div id="custom_select">
    <div id="current_option" data-value="">
        <span>------------</span>
        <b><img src="http://support.eye.fi/wp-content/uploads/2007/09/arrow-down.png.pagespeed.ce.sb6_oS5SGc.png"/></b>
    </div>
        <ul id="custom_options">
            <li data-value="">----------</li>
            <li data-value="1">Opt1</li>
            <li data-value="2">Opt2</li>
            <li data-value="3">Opt3</li>
        </ul>
</div>

Тут есть селект настоящий и полностью с ним синхронизированных кастомный. В роли аттрибута value выступает у кастомного data-value.

5
  • Идею понял. Предположим, я создам свой собственный селект. Чтобы передать необходимые данные на сервер, мне нужно создать нормальный селект с такими же значениями, скрыть его и синхронизировать со своим?
    – andreyqin
    13 мая 2014 в 10:14
  • Ну да, смотря как передаются данные, если это ajax запрос и данные собираются вручную, то можно и не создавать обычный, а если это классическая форма, с кнопкой submit, то, конечно, удобно синхронизировать и отправлять данные с формы, как всегда это делается.
    – iterq
    13 мая 2014 в 10:17
  • jsfiddle.net/8vFLy/5 с JQuery 1.10.1 не работало в опере. С 2.1.0 - все ок.
    – iterq
    13 мая 2014 в 10:33
  • А как сделать, чтобы при клике вне области нашего псевдоселекта он закрывался?
    – andreyqin
    13 мая 2014 в 10:58
  • Переписал ваш код - jsfiddle.net/8vFLy/6 Работает, начиная с версии 1.7.2
    – andreyqin
    13 мая 2014 в 11:10
1

Доделал, чтобы работало и в обратном направлении. Например, для случаев, когда этот селект загружается со значением.

$("#current_option").click(function() {
  customOptionsBlock = $("#custom_options");
  if (customOptionsBlock.is(":hidden")) {
    $("#custom_options").show();
  } else {
    $("#custom_options").hide();
  }
});

$("#custom_options li").click(function() {
  choosenValue = $(this).attr("data-value");
  $("select").val(choosenValue).prop("selected", true);
  $("#current_option span").text($(this).text());
  $("#current_option").attr("data-value", choosenValue);
});

$('select').change(function() {
  $('#current_option').attr("data-value", $(this).val());
  $("#current_option span").text($('select :selected').text());
});
#custom_select {
  width: 100px;
  text-align: center;
}
#current_option {
  width: 100%;
  background: #d2d2d2;
  border: 1px solid grey;
  line-height: 25px;
  cursor: pointer;
  border-radius: 4px;
}
#current_option:hover {
  background: #EBEBEB;
}
#current_option b {
  height: 100%;
  width: 20px;
  float: right;
  border-left: 1px solid grey;
}
#current_option b img {
  width: 10px;
  height: 10px;
  margin-top: 5px;
}
#custom_options {
  display: none;
  width: 100%;
  padding: 0;
  margin-top: -2px;
  background: #EBEBEB;
  border: 1px solid grey;
  border-radius: 0 0 4px 4px;
}
#custom_options li {
  list-style: none;
  padding: 0;
  width: 100%;
  height: 25px;
  text-align: center;
}
#custom_options li:last-child {
  border-radius: 0 0 4px 4px;
}
#custom_options li:first-child {
  margin-top: 4px;
}
#custom_options li:hover {
  background: #d2d2d2;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<select>
  <option value="">--------</option>
  <option value="1">Opt1</option>
  <option value="2">Opt2</option>
  <option value="3">Opt3</option>
</select>

<div id="custom_select">
  <div id="current_option" data-value="">
    <span>------------</span>
    <b><img src="http://support.eye.fi/wp-content/uploads/2007/09/arrow-down.png.pagespeed.ce.sb6_oS5SGc.png"/></b>
  </div>
  <ul id="custom_options">
    <li data-value="">----------</li>
    <li data-value="1">Opt1</li>
    <li data-value="2">Opt2</li>
    <li data-value="3">Opt3</li>
  </ul>
</div>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.