65 lines
2.9 KiB
Plaintext
65 lines
2.9 KiB
Plaintext
<!DOCTYPE html>
|
|
<html lang="zh-CN">
|
|
<head>
|
|
<meta charset="UTF-8" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
<title>Aurora Admin · AutoComplete</title>
|
|
<link rel="stylesheet" href="../.design_library/aurora-admin/colors_and_type.css" />
|
|
<link rel="stylesheet" href="./AutoComplete.css" />
|
|
</head>
|
|
<body>
|
|
<div class="aa-page">
|
|
<h2 class="aa-h2">AutoComplete 自动完成</h2>
|
|
<p class="aa-desc">输入时匹配建议,高亮关键字,支持键盘上下选择与回车。</p>
|
|
|
|
<div class="aa-demo">
|
|
<div class="aa-autocomplete" id="ac">
|
|
<input class="aa-autocomplete-input" id="input" placeholder="输入城市,如「北」" />
|
|
<div class="aa-autocomplete-pop" id="pop" style="display:none"></div>
|
|
</div>
|
|
<p class="aa-code-tip" id="out">试试输入:北京、上海、广州…</p>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
var data = ['北京', '上海', '广州', '深圳', '杭州', '成都', '重庆', '武汉', '西安', '南京', '苏州', '天津'];
|
|
var root = document.getElementById('ac');
|
|
var input = document.getElementById('input');
|
|
var pop = document.getElementById('pop');
|
|
var out = document.getElementById('out');
|
|
var active = -1, list = [];
|
|
|
|
function highlight(text, q) {
|
|
if (!q) return text;
|
|
return text.replace(new RegExp('(' + q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'g'), '<mark>$1</mark>');
|
|
}
|
|
function render() {
|
|
if (!list.length) { pop.style.display = 'none'; return; }
|
|
pop.style.display = 'block';
|
|
pop.innerHTML = list.map(function (it, i) {
|
|
return '<div class="aa-autocomplete-item' + (i === active ? ' is-active' : '') + '" role="option" data-i="' + i + '">' + highlight(it, input.value.trim()) + '</div>';
|
|
}).join('');
|
|
}
|
|
input.addEventListener('input', function () {
|
|
var q = input.value.trim();
|
|
active = -1;
|
|
list = q ? data.filter(function (d) { return d.indexOf(q) >= 0; }) : [];
|
|
render();
|
|
});
|
|
input.addEventListener('keydown', function (e) {
|
|
if (pop.style.display === 'none') return;
|
|
if (e.key === 'ArrowDown') { e.preventDefault(); active = Math.min(list.length - 1, active + 1); render(); }
|
|
else if (e.key === 'ArrowUp') { e.preventDefault(); active = Math.max(0, active - 1); render(); }
|
|
else if (e.key === 'Enter' && active >= 0) { choose(active); }
|
|
else if (e.key === 'Escape') { pop.style.display = 'none'; }
|
|
});
|
|
function choose(i) { input.value = list[i]; out.textContent = '已选择:' + list[i]; pop.style.display = 'none'; }
|
|
pop.addEventListener('click', function (e) {
|
|
var it = e.target.closest('.aa-autocomplete-item');
|
|
if (it) choose(parseInt(it.dataset.i, 10));
|
|
});
|
|
document.addEventListener('click', function (e) { if (!root.contains(e.target)) pop.style.display = 'none'; });
|
|
</script>
|
|
</body>
|
|
</html>
|