一個簡單css+js的開關組件


一個簡單的開關組件

 

依賴:jquery.js

CSS

.choose-btn { display: none; }
.choose-label { box-shadow: #b1b1b1 0px 0px 0px 1px; width: 30px; height: 16px; display: inline-block; border-radius: 16px; position: relative; background-color: #bdbdbd; overflow: hidden; margin: 0; margin-top: 4px; cursor: pointer; vertical-align: middle; }
.choose-label:before { content: ''; position: absolute; left: 0; width: 16px; height: 16px; display: inline-block; border-radius: 20px; background-color: #fff; z-index: 20; -webkit-transition: all 0.2s; transition: all 0.2s; }
.choose-btn:checked + label.choose-label:before { left: 14px; }
.choose-btn:checked + label.choose-label { background-color: #009cef; box-shadow: #009cef 0px 0px 0px 1px; }
.choose-text { display: inline-block; vertical-align: middle; line-height: 20px; color: #888; font-size: 12px; margin-top: 4px; }

JS

// 開關組件
$(".choose-btn").each(function(){
  var texts = $(this).attr('data-toggle').split('|');
  $(this).siblings('.choose-text').text(this.checked?texts[0]:texts[1]);
});
$(".choose-btn").on("change", function(){
  var texts = $(this).attr('data-toggle').split('|');
  $(this).siblings('.choose-text').text(this.checked?texts[0]:texts[1]);
});

HTML

<div>
    <input type="checkbox" name="switch1" id="switch1" class="choose-btn" data-toggle="開啟|關閉">
    <label for="switch1" class="choose-label"></label>
    <span class="choose-text"></span>
</div>

注意:

  1. input的id和label的for屬性值要一致
  2. data-toggle 的值用 | 分隔 是|否 的對應的文本
  3. 如果不需要顯示文本,可以把 choose-text 去掉
  4. 父節點不一定要是div,我這里放一個只是為了看起來像個整體


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM