複選框:html
閒話少說,這裏直接介紹如何修改小程序提供的複選框的樣式,如原生的是這樣的:web
須要的是這樣的:小程序
示例代碼:微信小程序
/*複選框外框樣式*/ checkbox .wx-checkbox-input { width: 40rpx; height: 40rpx; border: 4rpx solid #999; border-radius: 100%; } /*複選框外框選中樣式*/ checkbox .wx-checkbox-input.wx-checkbox-input-checked { border-color: #3cbcee; } /*複選框選中後內部樣式*/ checkbox .wx-checkbox-input.wx-checkbox-input-checked::before { width: 60%; height: 60%; background: #3cbcee; border-radius: 100%; content: ''; transform: translate(-50%, -50%) scale(1); -webkit-transform: translate(-50%, -50%) scale(1); }
注:複選框選中後內部樣式部分,最後兩行樣式必定要有,否則複選框選中後內部的圓點會不居中(並且不太好調),具體的就不細說了,有興趣的能夠試試:瀏覽器
transform: translate(-50%, -50%) scale(1);
-webkit-transform: translate(-50%, -50%) scale(1);
如上,仍是跟咱們修改html原生標籤樣式是同樣的,只不過咱們不瞭解小程序這些原生組件的內部結構罷了。微信
單選按鈕:優化
仍舊按上面的樣式修改,代碼以下:編碼
/* 單選按鈕樣式*/ radio .wx-radio-input { width: 40rpx; height: 40rpx; border: 4rpx solid #999; border-radius: 100%; background: none; } /*單選按鈕選中後內部樣式*/ radio .wx-radio-input.wx-radio-input-checked { border: 4rpx solid #3cbcee!important; } radio .wx-radio-input.wx-radio-input-checked::before { width: 60%; height: 60%; background: #3cbcee; border-radius: 100%; content: ''; transform: translate(-50%, -50%) scale(1); -webkit-transform: translate(-50%, -50%) scale(1); }
如上,樣式代碼跟複選框的基本一致,直接將checkbox換爲radio就能夠了。可是有一個地方不同,就是單選按鈕選擇後的外框樣式須要添加 !Important ,否則不會生效的。spa
若是須要添加禁用標誌,也是能夠自定義的:code
radio.disabled .wx-radio-input { width: 40rpx; height: 40rpx; border: 4rpx solid #eee; border-radius: 100%; background: none; }
總結:
雖然官方沒有提供原生組件樣式修改的入口,可是微信小程序基於微信內置瀏覽器的X5內核(其實就是Chrome內核),小程序在某些方面和html是很相似的。從上邊的例子也能夠看出,小程序原生checkbox組件內部是封裝了一些咱們看不到的東西的,只要咱們瞭解了原生組件內部構造,就能夠直接修改組件樣式。
目前還沒找到有關小程序組件內部類名的相關文檔,但感受能夠從小程序編譯包中應該有跡可循的,感興趣的能夠去了解下:http://www.javashuo.com/article/p-fkdzmaxk-cz.html
後記:
對於複選框、單選按鈕這些組件,在編碼實現的時候,會涉及到組件的選中、非選中、禁用狀態,非禁用狀態可能會有默認選擇第一個選項,通常狀況下的編碼以下:
<radio wx:if="{{item.isSelect==0}}" class='vc {{cardDetail.status!=1||cardDetail.payStatus==0?"disabled":""}}' color="white" disabled='{{cardDetail.status!=1||cardDetail.payStatus==0}}' value="{{index}}" checked='{{index==fatherRightsCheckIndex}}' />
如上,全部的狀態、屬性都在一個組件中實現,能夠發現判斷條件會比較多,若是後續有改動,那麼改動的地方就比較多了。咱們能夠對這段代碼進行優化以下:
<block wx:if="{{item.isSelect==0}}"> <radio wx:if="{{cardDetail.status!=1||cardDetail.payStatus==0}}" class='vc disabled' disabled='true' /> <radio wx:else class='vc' color="white" value="{{index}}" checked='{{index==fatherRightsCheckIndex}}' /> </block>
如上,代碼並無增長多少,可是代碼結構清晰多了,即便後續有改動,改動起來也很方便的。