ドロップダウン
jQuery Mobileにはドロップダウンは標準でもあるのですが、いろいろ痛い目に合わされるので、ボタンとポップアップで作ってみます
/* * ドロップダウン */ interface DropdownOptions { alignRight?: boolean; onSelected?: (selItem: Dropdown.Item) => void; // 選択された onClosed?: any; // 閉じられた } namespace Dropdown { "use strict"; export class Item { text: string; value: any; constructor(text?: string, value?: any) { this.text = text; this.value = value; } } /* * ドロップダウンリスト表示 */ export function open(selector: JQuery | string, items: Item[], options?: DropdownOptions) { let target = $(selector); let style = "min-height:1em;"; if (options && options.alignRight) { style += "text-align:right;"; } let content = ""; content += "<div"; content += " data-role='popup'"; content += " data-history='false'"; content += " data-dismissible='true'"; content += ">"; content += " <div role='main' class='ui-content'>"; content += " <ul data-role='listview' data-icon='false'>"; for (let i = 0; i < items.length; i++) { content += " <li idx=" + i + ">"; content += " <a href='#' style='" + style + "'>" + items[i].text + "</a>"; content += " </li >"; } content += " </ul>"; content += " </div>"; content += "</div>"; // ポップアップ作成 let box = $(content) .appendTo(cm.getActivePage()) .enhanceWithin() .popup(); // 選択 box.find("li").off("click").on("click", function (event: Event) { let idx = parseInt($(this).attr("idx"), 0); if (options && options.onSelected) { options.onSelected(items[idx]); } Popup.close(); }); // 表示 let pos = Popup.Pos.downLeft(target); // 位置取得 if (options && options.alignRight) { pos = Popup.Pos.downRight(target); } Popup.open(box, { transition: "none" , positionFixed: false , x1: pos.x1 , y1: pos.y1 , x2: pos.x2 , y2: pos.y2 , onClosed: function () { box.remove(); if (options && options.onClosed) { options.onClosed(); } } }); } }
ポップアップの表示には以前に作成したものを使用します
コールバックはオプションで取得します
固有のCSSはありません
使い方
$(document).on("click", "#ボタンID", function (event: Event) { try { // Pageをoverflow:hideでないと2重スクロール Dropdown.open( $(this) , [ { text: "選択1", value: 1 } , { text: "選択2", value: 2 } , { text: "選択3", value: 3 } , { text: "選択4", value: 4 } , { text: "選択5選択5", value: 5 } ] , { onSelected: (selItem: Dropdown.Item) => { if (selItem) { $(this).text(selItem.text).attr("value", selItem.value); } } , onClosed: () => { console.log("dropdown closed"); } , alignRight: false }); } catch (e) { cm.showErrMsg(e); } });
Dropdown.Itemで表示するアイテムを作成してDropdown.Openします
コールバックはアロー式でやってみました
アロー式を使用した場合、thisは呼び出し元のままになります