自動完成 - Autocompletes

  { prefix: 'SP', title: '🔥SHARE.CO🔥經典香水吊卡 ➜ 糖果茉莉, 奇蹟罌粟, 能量麝香, 甜蜜莉莉' },
  { prefix: 'SPY', title: '🔥SHARE.CO🔥經典粉絲限定 VIP 方案' },
  { prefix: 'SW', title: '素TEE / 內褲 / 平口褲 ➜ 版型專為亞洲人身形設計' }
1
2
3
4
5
6
7
8
9
10
11
<pre>
  { prefix: 'SP', title: '🔥SHARE.CO🔥經典香水吊卡 ➜ 糖果茉莉, 奇蹟罌粟, 能量麝香, 甜蜜莉莉' },
  { prefix: 'SPY', title: '🔥SHARE.CO🔥經典粉絲限定 VIP 方案' },
  { prefix: 'SW', title: '素TEE / 內褲 / 平口褲 ➜ 版型專為亞洲人身形設計' }
</pre>

<label class="search-input">
  <i class="icon-search"></i>
  <input class="input" type="text" data-autocomplete data-offset-left="-26"
         placeholder="search something" />
</label>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import noop from 'lodash.noop'

export default function bindAutocompletes() {

  const dom = document.querySelector('[data-autocomplete]')

  if (! dom) {
    return noop
  }

  const { Autocomplete } = window.beyond

  const rows = [
    { prefix: 'SP', title: '🔥SHARE.CO🔥經典香水吊卡 ➜ 糖果茉莉, 奇蹟罌粟, 能量麝香, 甜蜜莉莉' },
    { prefix: 'SPY', title: '🔥SHARE.CO🔥經典粉絲限定 VIP 方案' },
    { prefix: 'SW', title: '素TEE / 內褲 / 平口褲 ➜ 版型專為亞洲人身形設計' }
  ]
  const autocomplete = new Autocomplete(dom, {

    async getData({ keyword }) {
      return rows.filter(({ prefix, title }) => {

        const upperKeyword = keyword.toUpperCase()
        const upperTitle = title.toUpperCase()
        const upperPrefix = prefix.toUpperCase()

        return upperPrefix.includes(upperKeyword) || upperTitle.includes(upperKeyword)
      })
    },
    itemClick(row) {
      return row.prefix
    }
  })

  return function unbindAutocompletes() {
    autocomplete.destroy()
  }
}

Autocomplete HTML

<label class="search-input">
  <i class="icon-search"></i>
  <input class="input"
         type="text"
         data-autocomplete
         data-offset-left="-26"
         placeholder="search something" />
</label>
屬性名稱 用途
data-offset-left 選單的 left 偏移值,例如希望選單可以往右偏移 20 px,data-offset-left="20"
data-offset-top 選單的 top 偏移值

Autocomplete JS

constructor

const autocomplete = new Autocomplete(dom, options)
名稱 型別 說明
dom HTMLElement 需要指定為 autocomplete 的元素
options object 選項
options.getData function 根據關鍵字取得選單資料,可以是 async function
options.itemClick function 決定要 return row 的哪一個屬性當作是 getData function 的關鍵字
options.renderMenuItem function 決定要用什麼 HTML 顯示 autocomplete 的 menu 選單

destroy

移除 autocomplete 產生的 dom 元素與 event listeners

autocomplete.destroy()