DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
用 CSS 打造自訂外觀的 select 下拉選單
編輯:CSS詳解     

原生 select 的外觀幾乎無法客製,各瀏覽器長得都不一樣。常見的解法是把真正的 select 疊在上層並設為全透明,下方放一個自己排版的假容器負責顯示,兩者位置完全重疊,使用者點到的其實還是原生下拉選單。

結構與樣式

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>下拉框</title>
<style>
* { margin: 0; padding: 0; }

body { padding: 50px 50px; }

.btn-select {
  position: relative;
  display: inline-block;
  width: 150px;
  height: 25px;
  background-color: #f80;
  font: 14px/20px "Microsoft YaHei";
  color: #fff;
}

.btn-select .cur-select {
  position: absolute;
  display: block;
  width: 150px;
  height: 25px;
  line-height: 25px;
  background: #f80 url(ico-arrow.png) no-repeat 125px center;
  text-indent: 10px;
}

.btn-select:hover .cur-select {
  background-color: #f90;
}

.btn-select select {
  position: absolute;
  top: 0;
  left: 0;
  width: 150px;
  height: 25px;
  opacity: 0;
  filter: alpha(opacity: 0);
  font: 14px/20px "Microsoft YaHei";
  color: #f80;
}

.btn-select select option { text-indent: 10px; }
.btn-select select option:hover {
  background-color: #f80;
  color: #fff;
}
</style>
</head>

HTML 與同步顯示的腳本

<body>
<form>
<a class="btn-select" id="btn_select">
<span class="cur-select">請選擇</span>
<select>
<option>選項一</option>
<option>選項二</option>
<option>選項三</option>
<option>選項四</option>
<option>選項五</option>
</select>
</a>
</form>

<script>
var $$ = function (id) {
  return document.getElementById(id);
}
window.onload = function () {
  var btnSelect = $$("btn_select");
  var curSelect = btnSelect.getElementsByTagName("span")[0];
  var oSelect = btnSelect.getElementsByTagName("select")[0];
  oSelect.onchange = function () {
    var text = oSelect.options[oSelect.selectedIndex].text;
    curSelect.innerHTML = text;
  }
}
</script>
</body>
</html>

關鍵在於 .btn-select select 的 opacity: 0 與 filter: alpha(opacity: 0):select 依然存在、依然可互動,只是看不見。真正呈現給使用者的是 .cur-select 這個 span,選項變動時由 onchange 把文字同步寫回去。這招的優點是完全保留原生下拉的鍵盤操作與選單行為,不必自己重刻互動邏輯。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved