类似百度输入框自动完成
1.前臺代碼
<%@ 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>搜索詞自動完成</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對象
??????????? var $searchInput = $search.find('#search-text');
??????????? //關閉瀏覽器提供給輸入框的自動完成
??????????? $searchInput.attr('autocomplete', 'off');
??????????? //創建自動完成的下拉列表,用于顯示服務器返回的數據,插入在搜索按鈕的后面,等顯示的時候再調整位置
??????????? var $autocomplete = $('<div></div>')
??????????? .hide()
??????????? .insertAfter('#submit');
??????????? //清空下拉列表的內容并且隱藏下拉列表區
??????????? var clear = function () {
??????????????? $autocomplete.empty().hide();
??????????? };
??????????? //注冊事件,當輸入框失去焦點的時候清空下拉列表并隱藏
??????????? $searchInput.blur(function () {
??????????????? setTimeout(clear, 500);
??????????? });
??????????? //下拉列表中高亮的項目的索引,當顯示下拉列表項的時候,移動鼠標或者鍵盤的上下鍵就會移動高亮的項目,想百度搜索那樣
??????????? var selectedItem = null;
??????????? //timeout的ID
??????????? var timeoutid = null;
??????????? //設置下拉項的高亮背景
??????????? var setSelectedItem = function (item) {
??????????????? //更新索引變量
??????????????? selectedItem = item;
??????????????? //按上下鍵是循環顯示的,小于0就置成最大的值,大于最大值就置成0
??????????????? if (selectedItem < 0) {
??????????????????? selectedItem = $autocomplete.find('li').length - 1;
??????????????? }
??????????????? else if (selectedItem > $autocomplete.find('li').length - 1) {
??????????????????? selectedItem = 0;
??????????????? }
??????????????? //首先移除其他列表項的高亮背景,然后再高亮當前索引的背景
??????????????? $autocomplete.find('li').removeClass('highlight')
??????????????? .eq(selectedItem).addClass('highlight');
??????????? };
??????????? var ajax_request = function () {
??????????????? //ajax服務端通信
??????????????? $.ajax({
??????????????????? 'url': 'InputAutoCompelete.aspx', //服務器的地址
??????????????????? 'data': { 'search-text': $searchInput.val() }, //參數
??????????????????? 'dataType': 'json', //返回數據類型
??????????????????? 'type': 'POST', //請求類型
??????????????????? 'success': function (data) {
??????????????????????? if (data.length) {
??????????????????????????? //遍歷data,添加到自動完成區
??????????????????????????? $.each(data, function (index, term) {
??????????????????????????????? //創建li標簽,添加到下拉列表中
??????????????????????????????? $('<li></li>').text(term).appendTo($autocomplete)
??????????????????????????????? .addClass('clickable')
??????????????????????????????? .hover(function () {
??????????????????????????????????? //下拉列表每一項的事件,鼠標移進去的操作
??????????????????????????????????? $(this).siblings().removeClass('highlight');
??????????????????????????????????? $(this).addClass('highlight');
??????????????????????????????????? selectedItem = index;
??????????????????????????????? }, function () {
??????????????????????????????????? //下拉列表每一項的事件,鼠標離開的操作
??????????????????????????????????? $(this).removeClass('highlight');
??????????????????????????????????? //當鼠標離開時索引置-1,當作標記
??????????????????????????????????? selectedItem = -1;
??????????????????????????????? })
??????????????????????????????? .click(function () {
??????????????????????????????????? //鼠標單擊下拉列表的這一項的話,就將這一項的值添加到輸入框中
??????????????????????????????????? $searchInput.val(term);
??????????????????????????????????? //清空并隱藏下拉列表
??????????????????????????????????? $autocomplete.empty().hide();
??????????????????????????????? });
??????????????????????????? });//事件注冊完畢
??????????????????????????? //設置下拉列表的位置,然后顯示下拉列表
??????????????????????????? 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();
??????????????????????? }
??????????????????? }
??????????????? });
??????????? };
??????????? //對輸入框進行事件注冊
??????????? $searchInput
??????????? .keyup(function (event) {
??????????????? //字母數字,退格,空格
??????????????? 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 代表鼠標離開
??????????????????? if (selectedItem == -1) {
??????????????????????? setSelectedItem($autocomplete.find('li').length - 1);
??????????????????? }
??????????????????? else {
??????????????????????? //索引減1
??????????????????????? setSelectedItem(selectedItem - 1);
??????????????????? }
??????????????????? event.preventDefault();
??????????????? }
??????????????? else if (event.keyCode == 40) {
??????????????????? //下
??????????????????? //selectedItem = -1 代表鼠標離開
??????????????????? if (selectedItem == -1) {
??????????????????????? setSelectedItem(0);
??????????????????? }
??????????????????? else {
??????????????????????? //索引加1
??????????????????????? setSelectedItem(selectedItem + 1);
??????????????????? }
??????????????????? event.preventDefault();
??????????????? }
??????????? })
??????????? .keypress(function (event) {
??????????????? //enter鍵
??????????????? if (event.keyCode == 13) {
??????????????????? //列表為空或者鼠標離開導致當前沒有索引值
??????????????????? 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();
??????????????? }
??????????? });
??????????? //注冊窗口大小改變的事件,重新調整下拉列表的位置
??????????? $(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">請輸入關鍵詞</label><input type="text" id="search-text" name="search-text" />
??????? <input type="button" id="submit" value="搜索" />
??? </div>
</body>
</html>
2.后臺代碼
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();
??????????????? }
??????????? }
??????? }
??? }
}
轉載于:https://www.cnblogs.com/kexb/p/5064983.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的类似百度输入框自动完成的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ajax传递复杂参数
- 下一篇: zepto点击事件兼容pc和mobile