對於表單,input[type="radio"] 的樣式老是不那麼友好,在不一樣的瀏覽器中表現不一。css
爲了最大程度的顯示出它們的差異,而且爲了好看,首先定義了一些樣式:html
html: <form action=""> <div class="sex"> <div class="female"> <label for="female">女</label> <input type="radio" name="sex" id="female"> </div> <div class="male"> <label for="male">男</label> <input type="radio" name="sex" id="male"> </div> </div> </form>
css: body { margin: 0; } input { padding: 0; margin: 0; border: 0; } .female, .male { position: relative; height: 40px; line-height: 40px; margin-left: 40px; } .sex label { display: block; height: 40px; width: 40px; line-height: 40px; font-size: 20px; cursor: pointer; } .sex input { z-index: 3; position: absolute; top: 0; bottom: 0; left: 40px; margin: auto; display: block; width: 30px; height: 30px; cursor: pointer; }
而後在各個瀏覽器中觀察,會發現有很大的差異:chrome
ie:瀏覽器
edge:this
opera:spa
chrome:firefox
firefox:3d
對於 firefox 瀏覽器,即使是設置了寬和高,依然是沒有效果,input[type="radio"] 的那個圓圈仍是初始狀態那麼大。其它瀏覽器的表現也不一致,爲了達到一致的效果,咱們須要作兼容處理。code
思路:orm
1. 將 input[type="radio"] 隱藏, opacity: 0; 置於上層,當咱們點擊它時,就能正確的響應本來的事件。
2. 自定義一個圓圈,置於下層,模擬本來類似的樣式;
3. 用 js 實現選中 input[type="radio"] 時,在其下層的自定義的元素改變原來的背景顏色。
代碼:
html: <form action=""> <div class="sex"> <div class="female"> <label for="female">女</label> <input type="radio" name="sex" id="female"> <span class="female-custom"></span> <!-- 同下面的 span 同樣做爲自定義的元素 --> </div> <div class="male"> <label for="male">男</label> <input type="radio" name="sex" id="male"> <span class="male-custom"></span> </div> </div> </form>
css: body { margin: 0; } input { padding: 0; margin: 0; border: 0; } .female, .male { position: relative; /* 設置爲相對定位,以便讓子元素能絕對定位 */ height: 40px; line-height: 40px; margin-left: 40px; } .sex label { display: block; height: 40px; width: 40px; line-height: 40px; font-size: 20px; cursor: pointer; } .sex input { z-index: 3; position: absolute; top: 0; bottom: 0; left: 40px; margin: auto; /* 這裏及以上的定位,可讓該元素豎直居中。(top: 0; bottom: 0;) */ opacity: 0; display: block; width: 30px; height: 30px; cursor: pointer; } .sex span { position: absolute; top: 0; bottom: 0; left: 40px; margin: auto; display: block; width: 25px; height: 25px; border: 1px solid #000; border-radius: 50%; cursor: pointer; } .sex span.active { background-color: #000; }
js: $("#male").click( function () { $(this).siblings("span").addClass("active"); $(this).parents("div").siblings("div").children("span").removeClass("active"); }); $("#female").click( function () { $(this).siblings("span").addClass("active"); $(this).parents("div").siblings("div").children("span").removeClass("active"); });
這樣處理後,在瀏覽器中展現效果所有同樣了:
擴展:
1. 對於代碼中出現的定位,對父元素使用 position: relative; 給子元素使用 position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; 能實現讓子元素相對於父元素居中(知足水平居中和豎直居中)顯示。若是隻是須要豎直居中,則不須要添加 right: 0; 和 left: 0; 的樣式。
2. 有時當咱們不容易肯定子元素的高度時,能夠這樣設置:對父元素 position: relative; 對子元素 position: absolute; top: 10px; bottom: 10px; margin: auto; 這樣一來,子元素的高度就是父元素的高度減去20px後的值了,一樣,top 和 bottom 支持百分數,可擴展性更強。