網上搜索“左右滑動開關”,結果有很多諸如:純CSS3左右滑動開關按鈕等。但事實上,這種按鈕是click事件觸發的。在手機網頁上用這種組件,對於IPhone用戶,見多了很多這種滑動按鈕,如果點擊觸發,會顯得很不協調。
說白了,網上的這種按鈕都是點擊按鈕而非滑動按鈕。我們現在要找一個滑動事件來替代click事件,最先想到的是touch相關的事件,后來在wscschool上找到了
Swipe事件:http://www.w3school.com.cn/jquerymobile/jquerymobile_events_touch.asp;。
這個解決方案需要引入jQuery Mobile;需要注意引入這個js后產生一系列的添加樣式。
代碼:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>無標題文檔</title> <style> /****去掉jquery mobile的loading****/ .ui-loader-default{ display:none} .ui-mobile-viewport{ border:none;} .ui-page {padding: 0; margin: 0; outline: 0} /******滑動開關按鈕*****/ .ui-switch { /*position: absolute;*/ font-size: 16px; /*right: 15px;*/ top: 6px; width: 52px; height: 22px; line-height: 1em; margin-right: 50px; margin-top: 5px; } .ui-switch .input { width: 52px; height: 22px; position: absolute; z-index: 10; border: 0; background: 0 0; -webkit-appearance: none; outline: 0 } .ui-switch .input:before { content: ''; width: 50px; height: 25px; border: 1px solid #dfdfdf; background-color: #fdfdfd; border-radius: 20px; cursor: pointer; display: inline-block; position: relative; vertical-align: middle; -webkit-user-select: none; user-select: none; -webkit-box-sizing: content-box; box-sizing: content-box; border-color: #dfdfdf; -webkit-box-shadow: #dfdfdf 0 0 0 0 inset; box-shadow: #dfdfdf 0 0 0 0 inset; -webkit-transition: border .4s, -webkit-box-shadow .4s; transition: border .4s, box-shadow .4s; -webkit-background-clip: content-box; background-clip: content-box } .ui-switch.cur .input:before { border-color: #ed6459; -webkit-box-shadow: #ed6459 0 0 0 16px inset; box-shadow: #ed6459 0 0 0 16px inset; background-color: #ed6459; transition: border .4s, box-shadow .4s, background-color 1.2s; -webkit-transition: border .4s, -webkit-box-shadow .4s, background-color 1.2s; background-color: #ed6459 } .ui-switch.cur .input:after { left: 27px } .ui-switch .input:after { content: ''; width: 25px; height: 25px; position: absolute; top: 1px; left: 0; border-radius: 100%; background-color: #fff; -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, .4); box-shadow: 0 1px 3px rgba(0, 0, 0, .4); -webkit-transition: left .2s; transition: left .2s } </style> </head> <body> <div> <label class="ui-switch"> <span class="input"></span> </label> </div> <script src="../../assets/js/jquery.min.js"></script> <script> //去掉 jquery mobile默認給input的添加,。順序在引入之前 $("input").attr('data-role','none'); $("select").attr('data-role','none'); </script> <script src="../../assets/js/jquery.mobile.js"></script> <script> $(".ui-switch").on('swipe',function(){ if($(this).attr("class").indexOf("cur")>0) { $(this).removeClass("cur"); } else{ $(this).addClass("cur"); } }); </script> </body> </html>
至此,從點擊的開關變成了滑動的開關。有點問題,其實只用到了jQuery Mobile中的
Swipe事件,其他的並沒有用到,有必要把這個事件單獨取出來引用。這個后期考慮吧~