类似百度输入框自动完成
1.前臺(tái)代碼
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="InputAutoCompelete.aspx.cs" Inherits="HraWeb.InputAutoCompelete" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
??? <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
??? <title></title>
</head>
<body>
??? <form id="form1" runat="server">
??????? <div>
??????? </div>
??? </form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
?"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
??? <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
??? <title>搜索詞自動(dòng)完成</title>
??? <style type="text/css">
??????? #search {
??????????? text-align: center;
??????????? position: relative;
??????? }
??????? .autocomplete {
??????????? border: 1px solid #9ACCFB;
??????????? background-color: white;
??????????? text-align: left;
??????? }
??????????? .autocomplete li {
??????????????? list-style-type: none;
??????????? }
??????? .clickable {
??????????? cursor: default;
??????? }
??????? .highlight {
??????????? background-color: #9ACCFB;
??????? }
??? </style>
??? <%--<script type="text/javascript" src="Scripts/jquery.js"></script>--%>
??? <script type="text/javascript">
??????? $(function () {
??????????? //取得div層
??????????? var $search = $('#search');
??????????? //取得輸入框JQuery對(duì)象
??????????? var $searchInput = $search.find('#search-text');
??????????? //關(guān)閉瀏覽器提供給輸入框的自動(dòng)完成
??????????? $searchInput.attr('autocomplete', 'off');
??????????? //創(chuàng)建自動(dòng)完成的下拉列表,用于顯示服務(wù)器返回的數(shù)據(jù),插入在搜索按鈕的后面,等顯示的時(shí)候再調(diào)整位置
??????????? var $autocomplete = $('<div></div>')
??????????? .hide()
??????????? .insertAfter('#submit');
??????????? //清空下拉列表的內(nèi)容并且隱藏下拉列表區(qū)
??????????? var clear = function () {
??????????????? $autocomplete.empty().hide();
??????????? };
??????????? //注冊(cè)事件,當(dāng)輸入框失去焦點(diǎn)的時(shí)候清空下拉列表并隱藏
??????????? $searchInput.blur(function () {
??????????????? setTimeout(clear, 500);
??????????? });
??????????? //下拉列表中高亮的項(xiàng)目的索引,當(dāng)顯示下拉列表項(xiàng)的時(shí)候,移動(dòng)鼠標(biāo)或者鍵盤(pán)的上下鍵就會(huì)移動(dòng)高亮的項(xiàng)目,想百度搜索那樣
??????????? var selectedItem = null;
??????????? //timeout的ID
??????????? var timeoutid = null;
??????????? //設(shè)置下拉項(xiàng)的高亮背景
??????????? var setSelectedItem = function (item) {
??????????????? //更新索引變量
??????????????? selectedItem = item;
??????????????? //按上下鍵是循環(huán)顯示的,小于0就置成最大的值,大于最大值就置成0
??????????????? if (selectedItem < 0) {
??????????????????? selectedItem = $autocomplete.find('li').length - 1;
??????????????? }
??????????????? else if (selectedItem > $autocomplete.find('li').length - 1) {
??????????????????? selectedItem = 0;
??????????????? }
??????????????? //首先移除其他列表項(xiàng)的高亮背景,然后再高亮當(dāng)前索引的背景
??????????????? $autocomplete.find('li').removeClass('highlight')
??????????????? .eq(selectedItem).addClass('highlight');
??????????? };
??????????? var ajax_request = function () {
??????????????? //ajax服務(wù)端通信
??????????????? $.ajax({
??????????????????? 'url': 'InputAutoCompelete.aspx', //服務(wù)器的地址
??????????????????? 'data': { 'search-text': $searchInput.val() }, //參數(shù)
??????????????????? 'dataType': 'json', //返回?cái)?shù)據(jù)類(lèi)型
??????????????????? 'type': 'POST', //請(qǐng)求類(lèi)型
??????????????????? 'success': function (data) {
??????????????????????? if (data.length) {
??????????????????????????? //遍歷data,添加到自動(dòng)完成區(qū)
??????????????????????????? $.each(data, function (index, term) {
??????????????????????????????? //創(chuàng)建li標(biāo)簽,添加到下拉列表中
??????????????????????????????? $('<li></li>').text(term).appendTo($autocomplete)
??????????????????????????????? .addClass('clickable')
??????????????????????????????? .hover(function () {
??????????????????????????????????? //下拉列表每一項(xiàng)的事件,鼠標(biāo)移進(jìn)去的操作
??????????????????????????????????? $(this).siblings().removeClass('highlight');
??????????????????????????????????? $(this).addClass('highlight');
??????????????????????????????????? selectedItem = index;
??????????????????????????????? }, function () {
??????????????????????????????????? //下拉列表每一項(xiàng)的事件,鼠標(biāo)離開(kāi)的操作
??????????????????????????????????? $(this).removeClass('highlight');
??????????????????????????????????? //當(dāng)鼠標(biāo)離開(kāi)時(shí)索引置-1,當(dāng)作標(biāo)記
??????????????????????????????????? selectedItem = -1;
??????????????????????????????? })
??????????????????????????????? .click(function () {
??????????????????????????????????? //鼠標(biāo)單擊下拉列表的這一項(xiàng)的話,就將這一項(xiàng)的值添加到輸入框中
??????????????????????????????????? $searchInput.val(term);
??????????????????????????????????? //清空并隱藏下拉列表
??????????????????????????????????? $autocomplete.empty().hide();
??????????????????????????????? });
??????????????????????????? });//事件注冊(cè)完畢
??????????????????????????? //設(shè)置下拉列表的位置,然后顯示下拉列表
??????????????????????????? var ypos = $searchInput.position().top;
??????????????????????????? var xpos = $searchInput.position().left;
??????????????????????????? $autocomplete.css('width', $searchInput.css('width'));
??????????????????????????? $autocomplete.css({ 'position': 'relative', 'left': xpos + "px", 'top': ypos + "px" });
??????????????????????????? setSelectedItem(0);
??????????????????????????? //顯示下拉列表
??????????????????????????? $autocomplete.show();
??????????????????????? }
??????????????????? }
??????????????? });
??????????? };
??????????? //對(duì)輸入框進(jìn)行事件注冊(cè)
??????????? $searchInput
??????????? .keyup(function (event) {
??????????????? //字母數(shù)字,退格,空格
??????????????? if (event.keyCode > 40 || event.keyCode == 8 || event.keyCode == 32) {
??????????????????? //首先刪除下拉列表中的信息
??????????????????? $autocomplete.empty().hide();
??????????????????? clearTimeout(timeoutid);
??????????????????? timeoutid = setTimeout(ajax_request, 100);
??????????????? }
??????????????? else if (event.keyCode == 38) {
??????????????????? //上
??????????????????? //selectedItem = -1 代表鼠標(biāo)離開(kāi)
??????????????????? if (selectedItem == -1) {
??????????????????????? setSelectedItem($autocomplete.find('li').length - 1);
??????????????????? }
??????????????????? else {
??????????????????????? //索引減1
??????????????????????? setSelectedItem(selectedItem - 1);
??????????????????? }
??????????????????? event.preventDefault();
??????????????? }
??????????????? else if (event.keyCode == 40) {
??????????????????? //下
??????????????????? //selectedItem = -1 代表鼠標(biāo)離開(kāi)
??????????????????? if (selectedItem == -1) {
??????????????????????? setSelectedItem(0);
??????????????????? }
??????????????????? else {
??????????????????????? //索引加1
??????????????????????? setSelectedItem(selectedItem + 1);
??????????????????? }
??????????????????? event.preventDefault();
??????????????? }
??????????? })
??????????? .keypress(function (event) {
??????????????? //enter鍵
??????????????? if (event.keyCode == 13) {
??????????????????? //列表為空或者鼠標(biāo)離開(kāi)導(dǎo)致當(dāng)前沒(méi)有索引值
??????????????????? if ($autocomplete.find('li').length == 0 || selectedItem == -1) {
??????????????????????? return;
??????????????????? }
??????????????????? $searchInput.val($autocomplete.find('li').eq(selectedItem).text());
??????????????????? $autocomplete.empty().hide();
??????????????????? event.preventDefault();
??????????????? }
??????????? })
??????????? .keydown(function (event) {
??????????????? //esc鍵
??????????????? if (event.keyCode == 27) {
??????????????????? $autocomplete.empty().hide();
??????????????????? event.preventDefault();
??????????????? }
??????????? });
??????????? //注冊(cè)窗口大小改變的事件,重新調(diào)整下拉列表的位置
??????????? $(window).resize(function () {
??????????????? var ypos = $searchInput.position().top;
??????????????? var xpos = $searchInput.position().left;
??????????????? $autocomplete.css('width', $searchInput.css('width'));
??????????????? $autocomplete.css({ 'position': 'relative', 'left': xpos + "px", 'top': ypos + "px" });
??????????? });
??????? });
??? </script>
</head>
<body>
??? <div id="search">
??????? <label for="search-text">請(qǐng)輸入關(guān)鍵詞</label><input type="text" id="search-text" name="search-text" />
??????? <input type="button" id="submit" value="搜索" />
??? </div>
</body>
</html>
2.后臺(tái)代碼
using HraWeb.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace HraWeb
{
??? public partial class InputAutoCompelete : BasePage
??? {
??????? protected void Page_Load(object sender, EventArgs e)
??????? {
??????????? if (!string.IsNullOrEmpty(Request["search-text"]))
??????????? {
??????????????? string[] words = {"amani","abc","apple","abstract","an","bike","byebye",
"beat","be","bing","come","cup","class","calendar","china"};
??????????????? string key = Request["search-text"];
??????????????? if (key.Length != 0)
??????????????? {
??????????????????? List<string> jsonList = new List<string>();
??????????????????? for (int i = 0; i < words.Length; i++)
??????????????????? {
??????????????????????? if (words[i].Contains(key))
??????????????????????? {
??????????????????????????? jsonList.Add(words[i]);
??????????????????????? }
??????????????????? }
??????????????????? var json=Newtonsoft.Json.JsonConvert.SerializeObject(jsonList);
??????????????????? HttpContext.Current.Response.Write(json);
??????????????????? HttpContext.Current.Response.End();
??????????????? }
??????????? }
??????? }
??? }
}
轉(zhuǎn)載于:https://www.cnblogs.com/kexb/p/5064983.html
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專(zhuān)家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的类似百度输入框自动完成的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: ajax传递复杂参数
- 下一篇: zepto点击事件兼容pc和mobile