Option 對象
Option 對象代表 HTML 表單中下拉列表中的一個選項。
在 HTML 表單中 <option> 標簽每出現一次,一個 Option 對象就會被創建。
您可通過表單的 elements[] 數組訪問一個 Option 對象,或者通過使用 document.getElementById()。
Option 對象屬性
W3C: W3C 標準。
屬性 | 描述 | W3C |
---|---|---|
defaultSelected | 返回 selected 屬性的默認值。 | Yes |
disabled | 設置或返回選項是否應被禁用。 | Yes |
form | 返回對包含選項的表單的引用 | Yes |
index | 返回對包含該元素的 <form> 元素的引用。 | Yes |
selected | 設置或返回 selected 屬性的值。 | Yes |
text | 設置或返回某個選項的純文本值。 | Yes |
value | 設置或返回被送往服務器的值。 | Yes |
標準屬性和事件
Option 對象同樣支持標準的 屬性 和 事件。
如您還有不明白的可以在下面與我留言或是與我探討QQ群308855039,我們一起飛!
HTML中使用 <select> 和 <option> 元素創建選擇框。而 <select> 元素對應的是 HTMLSelectElement 接口,<option> 元素對應的是 HTMLOptionElement 接口。這兩個接口都是通過 HTMLElement 接口從其他 HTML 元素共享所有屬性和方法。
先從 <select> 元素對應的 HTMLSelectElement 接口開始介紹專屬的屬性和方法。
下面介紹一下<select> 元素根據不同選中狀態下的value屬性的值:
<select name="location" id="selLocation">
<option value="Sunnyvale, CA">Sunnyvale</option>
<option value="Los Angeles, CA">Los Angeles</option>
<option value="Mountain View, CA">Mountain View</option>
<option value="">China</option>
<option>Australia</option>
</select>
當選中選項框中的第一項時,<select> 元素的 value 值為 "Sunnyvale, CA";而選中第四項時,<select> 元素的 value 值為 "",因為該項的 value 屬性是空字符串;選中最后一項,則 value 值為 "Australia",因為該 <option> 元素沒有指定 value 屬性。
因此,根據以上的例子,<select> 元素的value屬性根據以下規則獲取值:
再介紹 <option> 元素對應的 HTMLOptionElement 接口專屬屬性和方法。
這里強調一下,<select> 元素的 change 事件與其它表單字段是不一樣的。其它表單字段會在自己的值改變后觸發 change 事件,然后字段失去焦點。而 <select> 會在選中一項時立即觸發 change 事件。
對于只允許選擇一項的 <select> 元素,獲取選項最簡單的方式是使用 <select> 元素的 selectIndex 屬性,如下面的例子:
let selectedOption = selectbox.options[selectbox.selectedIndex];
獲取到 <option> 元素后,就可以根據 <option> 元素的屬性和方法獲取想要的信息。
對于允許多選的 <select> 元素,selectedIndex 屬性就像只允許選擇一項一樣。設置 selectedIndex 會移除所有選項,只選擇指定的項,而獲取 selectedIndex 只會返回選中的第一項的索引。
選項還可以通過取得選項的引用并將其 selected 屬性設置為 true 來選中。例如,以下代碼會選中 <select> 的第一項:
selectbox.options[0].selected = true;
與 selectedIndex 不同,設置選項的 selected 屬性不會在多選時移除其他選項,從而可以動態選擇任意多個選項。如果修改單選框中選項的 selected 屬性,則其他選項會被移除。要注意的是,把 selected 屬性設置為 false 對單選框沒有影響。
通過 selected 屬性可以確定選擇框中哪個選項被選中。要取得所有選中項,需要循環選項集合逐一檢測 selected 屬性,比如:
function getSelectedOptions(selectbox){
let result = new Array();
for (let option of selectbox.options) {
if (option.selected) {
result.push(option);
}
}
return result;
}
可以使用 JavaScript 動態創建選項并將它們添加到選擇框。首先,可以使用 DOM 方法,如下所示:
let newOption = document.createElement("option");
newOption.appendChild(document.createTextNode("Option text"));
newOption.setAttribute("value", "Option value");
selectbox.appendChild(newOption);
以上代碼創建了一個新的<option>元素,使用文本節點添加文本,設置其 value 屬性,然后將其添加到選擇框。添加到選擇框之后,新選項會立即顯示出來。
瀏覽器原生提供 Option() 構造函數創建 HTMLOptionElement 實例:
new Option(text, value, defaultSelected, selected) : HTMLOptionElement
來看案例:
let newOption = new Option("Option Text", "Option Value", true);
創建之后,需要將該實例添加到 HTML 的 <select> 元素中,這里有兩種添加方法:
這里詳細介紹下 add() 方法:
add(element: HTMLOptionElement | HTMLOptGroupElement, before?: HTMLElement | number | null): void;
如果想要符合所有瀏覽器的規范,可以傳入 undefined 作為第二個參數。
let newOption = new Option("Option text", "Option value", true);
selectbox.add(newOption, undefined);
這里注意一下 defaultSelected 和 selected 兩個參數,有時候容易弄混。selected 屬性為 true 時,該 <option> 當前狀態處于已選擇狀態。defaultSelected 屬性為 true 時,表示 <option> 在默認情況下為已選擇狀態,但不代表 <option> 的當前狀態是已選擇狀態。當頁面重置時,selected 屬性值為 true 的 <option> 可能會變成未選擇狀態,而 defaultSelected 屬性值為 true 的 <option> 則一定會變成已選擇狀態。
移除 <option> 元素的方法也不止一種,下面列舉的方法都可以實現:
要清除選擇框的所有選項,需要迭代所有選項并逐一移除它們,如下面例子所示:
function clearSelectbox(selectbox) {
for (let index = 0; index < selectbox.options.length;) {
selectbox.remove(0);
}
}
使用 DOM 操作中的 appendChild() 方法實現從一個 <select> 元素中將 <option> 移到另一個 <select> 元素中,這種實現方法會將 <option> 元素先從其父元素中移除,然后再插入指定位置。如下所示:
let selectbox1 = document.getElementById("selLocations1");
let selectbox2 = document.getElementById("selLocations2");
selecbox2.appendChild(selectbox1.options[0]);
移動選項和移除選項都會導致每個 <option> 的 index 屬性重置。
重排 <option> 的話,使用 DOM 操作中的 insertBefore() 方法,而移到最后位置,還是使用 appendChild() 方法較為方便。
下面的代碼演示了將一個 <option> 在 <select> 中前移一個位置:
let optToMove = selectbox.options[1];
selectbox.insertBefore(optToMove, selectbox.options[optionToMove.index-1]);
這個例子首先獲得要移動 <option> 的索引,然后將其插入之前位于它前面的 <option> 之前,其中第二行代碼適用于除第一個 <option> 之外的所有 <option>。下面的代碼則可以將<option>向下移動一個位置:
let optionToMove = selectbox.options[1];
selectbox.insertBefore(optionToMove,
selectbox.options[optionToMove.index+2]);
<select> 和 <option> 是在 HTML 頁面布局時,經常使用的表單控件,學會使用與之對應的 HTMLSelectElement 和 HTMLOptionElement 接口中的屬性和方法會很容易的操控 <select> 和 <option> 元素。借助于 DOM 操作 <select> 和 <option> 也較為方便。
果圖
各位朋友大家早上好!
今天給大家帶來的是 八種select下拉選擇特效源碼!
在日常工作中會經常遇到!
大家可以按照自己的意愿,做成喜歡的樣子!
有想要文件版源碼的可以私聊小編!
廢話不多說,上源碼!
/**
* selectFx.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2014, Codrops
* http://www.codrops.com
*/
;( function( window ) {
'use strict';
/**
* based on from https://github.com/inuyaksa/jquery.nicescroll/blob/master/jquery.nicescroll.js
*/
function hasParent( e, p ) {
if (!e) return false;
var el = e.target||e.srcElement||e||false;
while (el && el != p) {
el = el.parentNode||false;
}
return (el!==false);
};
/**
* extend obj function
*/
function extend( a, b ) {
for( var key in b ) {
if( b.hasOwnProperty( key ) ) {
a[key] = b[key];
}
}
return a;
}
/**
* SelectFx function
*/
function SelectFx( el, options ) {
this.el = el;
this.options = extend( {}, this.options );
extend( this.options, options );
this._init();
}
/**
* SelectFx options
*/
SelectFx.prototype.options = {
// if true all the links will open in a new tab.
// if we want to be redirected when we click an option, we need to define a data-link attr on the option of the native select element
newTab : true,
// when opening the select element, the default placeholder (if any) is shown
stickyPlaceholder : true,
// callback when changing the value
onChange : function( val ) { return false; }
}
/**
* init function
* initialize and cache some vars
*/
SelectFx.prototype._init = function() {
// check if we are using a placeholder for the native select box
// we assume the placeholder is disabled and selected by default
var selectedOpt = this.el.querySelector( 'option[selected]' );
this.hasDefaultPlaceholder = selectedOpt && selectedOpt.disabled;
// get selected option (either the first option with attr selected or just the first option)
this.selectedOpt = selectedOpt || this.el.querySelector( 'option' );
// create structure
this._createSelectEl();
// all options
this.selOpts = [].slice.call( this.selEl.querySelectorAll( 'li[data-option]' ) );
// total options
this.selOptsCount = this.selOpts.length;
// current index
this.current = this.selOpts.indexOf( this.selEl.querySelector( 'li.cs-selected' ) ) || -1;
// placeholder elem
this.selPlaceholder = this.selEl.querySelector( 'span.cs-placeholder' );
// init events
this._initEvents();
}
/**
* creates the structure for the select element
*/
SelectFx.prototype._createSelectEl = function() {
var self = this, options = '', createOptionHTML = function(el) {
var optclass = '', classes = '', link = '';
if( el.selectedOpt && !this.foundSelected && !this.hasDefaultPlaceholder ) {
classes += 'cs-selected ';
this.foundSelected = true;
}
// extra classes
if( el.getAttribute( 'data-class' ) ) {
classes += el.getAttribute( 'data-class' );
}
// link options
if( el.getAttribute( 'data-link' ) ) {
link = 'data-link=' + el.getAttribute( 'data-link' );
}
if( classes !== '' ) {
optclass = 'class="' + classes + '" ';
}
return '<li ' + optclass + link + ' data-option data-value="' + el.value + '"><span>' + el.textContent + '</span></li>';
};
[].slice.call( this.el.children ).forEach( function(el) {
if( el.disabled ) { return; }
var tag = el.tagName.toLowerCase();
if( tag === 'option' ) {
options += createOptionHTML(el);
}
else if( tag === 'optgroup' ) {
options += '<li class="cs-optgroup"><span>' + el.label + '</span><ul>';
[].slice.call( el.children ).forEach( function(opt) {
options += createOptionHTML(opt);
} )
options += '</ul></li>';
}
} );
var opts_el = '<div class="cs-options"><ul>' + options + '</ul></div>';
this.selEl = document.createElement( 'div' );
this.selEl.className = this.el.className;
this.selEl.tabIndex = this.el.tabIndex;
this.selEl.innerHTML = '<span class="cs-placeholder">' + this.selectedOpt.textContent + '</span>' + opts_el;
this.el.parentNode.appendChild( this.selEl );
this.selEl.appendChild( this.el );
}
/**
* initialize the events
*/
SelectFx.prototype._initEvents = function() {
var self = this;
// open/close select
this.selPlaceholder.addEventListener( 'click', function() {
self._toggleSelect();
} );
// clicking the options
this.selOpts.forEach( function(opt, idx) {
opt.addEventListener( 'click', function() {
self.current = idx;
self._changeOption();
// close select elem
self._toggleSelect();
} );
} );
// close the select element if the target it′s not the select element or one of its descendants..
document.addEventListener( 'click', function(ev) {
var target = ev.target;
if( self._isOpen() && target !== self.selEl && !hasParent( target, self.selEl ) ) {
self._toggleSelect();
}
} );
// keyboard navigation events
this.selEl.addEventListener( 'keydown', function( ev ) {
var keyCode = ev.keyCode || ev.which;
switch (keyCode) {
// up key
case 38:
ev.preventDefault();
self._navigateOpts('prev');
break;
// down key
case 40:
ev.preventDefault();
self._navigateOpts('next');
break;
// space key
case 32:
ev.preventDefault();
if( self._isOpen() && typeof self.preSelCurrent != 'undefined' && self.preSelCurrent !== -1 ) {
self._changeOption();
}
self._toggleSelect();
break;
// enter key
case 13:
ev.preventDefault();
if( self._isOpen() && typeof self.preSelCurrent != 'undefined' && self.preSelCurrent !== -1 ) {
self._changeOption();
self._toggleSelect();
}
break;
// esc key
case 27:
ev.preventDefault();
if( self._isOpen() ) {
self._toggleSelect();
}
break;
}
} );
}
/**
* navigate with up/dpwn keys
*/
SelectFx.prototype._navigateOpts = function(dir) {
if( !this._isOpen() ) {
this._toggleSelect();
}
var tmpcurrent = typeof this.preSelCurrent != 'undefined' && this.preSelCurrent !== -1 ? this.preSelCurrent : this.current;
if( dir === 'prev' && tmpcurrent > 0 || dir === 'next' && tmpcurrent < this.selOptsCount - 1 ) {
// save pre selected current - if we click on option, or press enter, or press space this is going to be the index of the current option
this.preSelCurrent = dir === 'next' ? tmpcurrent + 1 : tmpcurrent - 1;
// remove focus class if any..
this._removeFocus();
// add class focus - track which option we are navigating
classie.add( this.selOpts[this.preSelCurrent], 'cs-focus' );
}
}
/**
* open/close select
* when opened show the default placeholder if any
*/
SelectFx.prototype._toggleSelect = function() {
// remove focus class if any..
this._removeFocus();
if( this._isOpen() ) {
if( this.current !== -1 ) {
// update placeholder text
this.selPlaceholder.textContent = this.selOpts[ this.current ].textContent;
}
classie.remove( this.selEl, 'cs-active' );
}
else {
if( this.hasDefaultPlaceholder && this.options.stickyPlaceholder ) {
// everytime we open we wanna see the default placeholder text
this.selPlaceholder.textContent = this.selectedOpt.textContent;
}
classie.add( this.selEl, 'cs-active' );
}
}
/**
* change option - the new value is set
*/
SelectFx.prototype._changeOption = function() {
// if pre selected current (if we navigate with the keyboard)...
if( typeof this.preSelCurrent != 'undefined' && this.preSelCurrent !== -1 ) {
this.current = this.preSelCurrent;
this.preSelCurrent = -1;
}
// current option
var opt = this.selOpts[ this.current ];
// update current selected value
this.selPlaceholder.textContent = opt.textContent;
// change native select element′s value
this.el.value = opt.getAttribute( 'data-value' );
// remove class cs-selected from old selected option and add it to current selected option
var oldOpt = this.selEl.querySelector( 'li.cs-selected' );
if( oldOpt ) {
classie.remove( oldOpt, 'cs-selected' );
}
classie.add( opt, 'cs-selected' );
// if there′s a link defined
if( opt.getAttribute( 'data-link' ) ) {
// open in new tab?
if( this.options.newTab ) {
window.open( opt.getAttribute( 'data-link' ), '_blank' );
}
else {
window.location = opt.getAttribute( 'data-link' );
}
}
// callback
this.options.onChange( this.el.value );
}
/**
* returns true if select element is opened
*/
SelectFx.prototype._isOpen = function(opt) {
return classie.has( this.selEl, 'cs-active' );
}
/**
* removes the focus class from the option
*/
SelectFx.prototype._removeFocus = function(opt) {
var focusEl = this.selEl.querySelector( 'li.cs-focus' )
if( focusEl ) {
classie.remove( focusEl, 'cs-focus' );
}
}
/**
* add to global namespace
*/
window.SelectFx = SelectFx;
} )( window );
*請認真填寫需求信息,我們會在24小時內與您取得聯系。