用HTML5 & jQuery创建一个简单的自动填充(autocomplete)

2014-02-11阅读(11040)评论(0)牵着狗狗看MM

W3Cways.com 微信公众号

AutoComplete就是指用户在文本框输入前几个字母或是汉字的时候,就能从存放数据的文本或是数据库里将所有以这些字母开头的数据提示给用户,供用户选择,提供方便。
html5-autocomplete-suggestions
HTML代码

[html]<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>输入自动完成及提示Demo</title>
<link rel="stylesheet" type="text/css" media="all" href="style.css">
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="js/jquery.autocomplete.min.js"></script>
<script type="text/javascript" src="js/currency-autocomplete.js"></script>
</head>

<body>
<div id="topbar"><a href="http://www.w3cways.com">返回web前端</a></div>
<div id="w">
<div id="content">
<h1>世界货币自动完成搜索</h1>
<p>示例只做了4种(输入值:人民币、美元、dollar、英镑)</p>

<div id="searchfield">
<form><input type="text" name="currency" class="biginput" id="autocomplete"></form>
</div><!– @end #searchfield –>

<div id="outputbox">
<p id="outputcontent">选择一种货币,其结果将在这里显示。</p>
</div>
</div><!– @end #content –>
</div><!– @end #w –>
</body>
</html>
[/html]

CSS代码(这里命名为style.css)

[css].autocomplete-suggestions { border: 1px solid #999; background: #fff; cursor: default; overflow: auto; }
.autocomplete-suggestion { padding: 10px 5px; font-size: 1.2em; white-space: nowrap; overflow: hidden; }
.autocomplete-selected { background: #f0f0f0; }
.autocomplete-suggestions strong { font-weight: normal; color: #3399ff; }
#searchfield { display: block; width: 100%; text-align: center; margin-bottom: 35px; }

#searchfield form {
display: inline-block;
background: #eeefed;
padding: 0;
margin: 0;
padding: 5px;
border-radius: 3px;
margin: 5px 0 0 0;
}
#searchfield form .biginput {
width: 600px;
height: 40px;
padding: 0 10px 0 10px;
background-color: #fff;
border: 1px solid #c8c8c8;
border-radius: 3px;
color: #aeaeae;
font-weight:normal;
font-size: 1.5em;
-webkit-transition: all 0.2s linear;
-moz-transition: all 0.2s linear;
transition: all 0.2s linear;
}
#searchfield form .biginput:focus {
color: #858585;
}
[/css]

JS代码

[js]$(function(){
var currencies = [
{ value: ‘人民币’, data: ‘¥’ },
{ value: ‘美元’, data: ‘$’ },
{ value: ‘dollar’, data: ‘$’ },
{ value: ‘英镑’, data: ‘£’ },
];

// 设置autocomplete从数组currencies拉取数据
$(‘#autocomplete’).autocomplete({
lookup: currencies,
onSelect: function (suggestion) {
var thehtml = ‘<strong>货币名称:</strong> ‘ + suggestion.value + ‘ <br> <strong>符号:</strong> ‘ + suggestion.data;
$(‘#outputcontent’).html(thehtml);
}
});
[/js]

Demo – 下载源码

转载请注明来源:Web前端(W3Cways.com) - Web前端学习之路 » 用HTML5 & jQuery创建一个简单的自动填充(autocomplete)
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!