天天看點

bootstrap-multiselect樣式修改

問題

bootstrap-multiselect是一款相當不錯的bootstrap風格下拉框元件,但是它的某些樣式我不是很喜歡,按鈕文本和下拉符号 “

” 都是居中的,且下拉清單的寬度也沒有跟随變動。

bootstrap-multiselect樣式修改
<script type="text/javascript">
    $(document).ready(function() {
        $('#example-dropRight').multiselect({
            buttonWidth: '400px',
            dropRight: true
        });
    });
</script>
           

需求

我不太喜歡這個樣式,現在我希望按鈕的文本和下拉符号 “

” 都右對齊,同時下拉清單的寬度與自适應為按鈕的寬度。

編碼

  • CSS
.multiselect-wrapper {
    display: inline-block;
    position: relative;
    vertical-align: middle;
    text-align: left;
}

    .multiselect-wrapper button {
        text-align: left;
    }

    .multiselect-wrapper span {
        margin-left: px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: block;
    }

    .multiselect-wrapper .dropdown-menu {
        width: %;
    }

    .multiselect-wrapper .caret {
        position: absolute;
        top: px;
        right: px;
        width: ;
        height: ;
    }

    .multiselect-wrapper label.checkbox, .multiselect-wrapper label.radio {
        padding: px px px px !important;
        width: %;
    }
           
  • JS 利用buttonContainer屬性,以自定義的multiselect-wrapper替換預設的 btn-group樣式。
$(function(){
    $('.multiselect').multiselect({
        buttonWidth: "100%",
        buttonContainer: "<div class='multiselect-wrapper' />"
    });
});
           
  • HTML
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
<link href="https://cdn.bootcss.com/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" rel="stylesheet">
<!DOCTYPE html>
<html lang="zh-cn">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="utf8" />
    </head>
    <body>
        <select name="department">
            <option value="true">物流部</option>
            <option value="false">設計部</option>
        </select>
        <script src="https://cdn.bootcss.com/jquery/2.1.4/jquery.js"></script>
        <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.js"></script>
        <script src="https://cdn.bootcss.com/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
    </body>
</html>
           
  • 示例
bootstrap-multiselect樣式修改
  • 補充

    bootstrap中對.dropdown-menu有個最小寬度的設定min-width: 160px,是以當buttonWidth低于160px時,下來清單的寬度并不會變化,如果有需求可以在.dropdown-menu中添加樣式min-width: 自定義寬度

繼續閱讀