jquery 仿文本编辑器(智能提示输入文字)
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">
String.prototype.trimStart = function (trimStr) {
if (!trimStr) { return this; }
var temp = this;
while (true) {
if (temp.substr(0, trimStr.length) != trimStr) {
break;
}
temp = temp.substr(trimStr.length);
}
return temp;
};
String.prototype.trimEnd = function (trimStr) {
if (!trimStr) { return this; }
var temp = this;
while (true) {
if (temp.substr(temp.length - trimStr.length, trimStr.length) != trimStr) {
break;
}
temp = temp.substr(0, temp.length - trimStr.length);
}
return temp;
};
String.prototype.trim = function (trimStr) {
var temp = trimStr;
if (!trimStr) { temp = " "; }
return this.trimStart(temp).trimEnd(temp);
};
String.prototype.endWith = function (endStr) {
var d = this.length - endStr.toString().length;
return (d >= 0 && this.lastIndexOf(endStr) == d)
}
var ciku = [];
function getSelectText2(id) {
var t = document.getElementById(id);
// alert("start=" + t.selectionStart + "end=" + t.selectionEnd);
if (window.getSelection) {
if (t.selectionStart != undefined && t.selectionEnd != undefined) {
selectionStart = t.selectionStart;
selectionEnd = t.selectionEnd;
return t.value.substring(t.selectionStart, t.selectionEnd);
} else {
return "";
}
} else {
return document.selection.createRange().text;
}
}
var dbClick = false;
var sel = false;
var selectionStart = "";
var selectionEnd = "";
$(function () {
$("#btn1").click(function () {
//alert(sel);
alert("input=" + $searchInput.val().length);
alert("selectionstart=" + selectionStart);
alert("selectionend=" + selectionEnd);
//alert(getSelectText2("search-text"));
});
$("#clear_Content").on("click", function () {
$("#search-text").val("");
ciku = [];
});
var cur_danci = "";
var lianci = "";
var curr = 0;
//取得div层
var $search = $('#search');
//取得输入框JQuery对象
var $searchInput = $search.find('#search-text');
//关闭浏览器提供给输入框的自动完成
$searchInput.attr('autocomplete', 'off');
//创建自动完成的下拉列表,用于显示服务器返回的数据,插入在搜索按钮的后面,等显示的时候再调整位置
var $autocomplete = $('<div></div>')
.hide()
.insertAfter('#submit');
var getTxt1CursorPosition = function (id) {
var oTxt1 = document.getElementById(id);
var cursurPosition = -1;
if (oTxt1.selectionStart) {//非IE浏览器
cursurPosition = oTxt1.selectionStart;
} else {//IE
var range = document.selection.createRange();
range.moveStart("character", -oTxt1.value.length);
cursurPosition = range.text.length;
}
return cursurPosition;
}
var ThroughStartFindEnd = function (start) {
if (start == "") {
start = "0";
}
var end = start;
var opt = ["+", "-", "*", "/", "(", ")", "="];
for (var ii = parseInt(start) ; ii < $searchInput.val().length; ii++) {
end = ii;
if (opt.indexOf($searchInput.val()[ii]) > -1) {
end = ii;
break;
}
}
return end;
// if (start.toString() == "0") {
// for (var ii = 0; ii< $searchInput.val().length; ii++) {
// if (opt.indexOf($searchInput.val()[ii]) > -1) {
// temp += "|";
// } else {
// temp += $searchInput.val()[ii];
// }
// }
// fenci = temp.trimEnd('|');
// var arr = fenci.split("|");
// start = FindN_1Length(arr);
// }
//var end = start;
//var opt = ["+", "-", "*", "/", "(", ")", "="];
// for (var i = start; i < $searchInput.val().length; i++) {
// if (opt.indexOf($searchInput.val()[i]) > -1) {
// i--;
// end = i;
// return end;
// break;
// }
// }
// return $searchInput.val().length;
}
var FindN_1Length = function (arr) {
var j = 0;
for (var i = 0; i < arr.length; i++) {
j += arr[i].length;
if (i > 0) { j = j + 1; }
}
return j;
}
var zhihoudanci = "";
var findLianci = function () {
var tibu_danci = "";
var danci = "";
var newSearchInputVal = "";
var start = 0;
var aliveopt = [];
var opt = ["+", "-", "*", "/", "(", ")", "="];
var fenci = new Array();
var temp = "";
for (var i = 0; i < $searchInput.val().length; i++) {
if (opt.indexOf($searchInput.val()[i]) > -1) {
temp += "|";
} else {
temp += $searchInput.val()[i];
}
}
fenci = temp.trimEnd('|');
var arr = fenci.split("|");
arr = $.grep(arr, function (n, i) {
return n != "" && n != " ";
});
if (arr.length > 0) {
tibu_danci = arr[0];
}
start = FindN_1Length(arr);
var start_ = "";
//if (selectionStart.toString() != "") {
// start_ = selectionStart;
//} else
{
start_ = getTxt1CursorPosition("search-text");
}
//if (zhihoudanci == "" || !zhihoudanci)
//{
zhihoudanci = $searchInput.val().substr(getTxt1CursorPosition("search-text"));
//}
var count = start;
count = ThroughStartFindEnd(start_);
temp = "";
for (var i = 0; i < count; i++) {
if (opt.indexOf($searchInput.val()[i]) > -1) {
temp += "|";
} else {
temp += $searchInput.val()[i];
}
}
fenci = temp.trimEnd('|');
arr = fenci.split("|");
arr = $.grep(arr, function (n, i) {
return n != "" && n != " ";
});
//if (start_ == $searchInput.val().length)
if (start_ ==count) {
start_ = start_ - arr[arr.length - 1].length;
}
if (arr.length > 0) {
cur_danci = arr[arr.length - 1];//$searchInput.val().substring(start_ - 1, count + 1);
} else {
cur_danci = tibu_danci;
}
if (opt.indexOf(cur_danci[0]) > -1) {
for (var i = 1; i < cur_danci.length; i++) {
danci += cur_danci[i];
}
}
if (danci != "")
cur_danci = danci;
cur_danci = cur_danci.trimEnd('+').trimEnd('-').trimEnd("*").trimEnd('/').trimEnd('(').trimEnd(')').trimEnd('(').trimEnd(')');
newSearchInputVal = $searchInput.val().substring(0, start_);//
if (opt.indexOf(newSearchInputVal[newSearchInputVal.length - 1]) <= -1 && newSearchInputVal != "") {
newSearchInputVal = $searchInput.val().substring(0, start_ - 1);//
}
if (opt.indexOf(newSearchInputVal[newSearchInputVal.length - 1]) <= -1) {
newSearchInputVal = $searchInput.val().substring(0, start_ - 2)
}
if (newSearchInputVal == ""&&$searchInput.val().length>1) {
newSearchInputVal = $searchInput.val().substring(0, start_+1);
}
return (newSearchInputVal);
}
//清空下拉列表的内容并且隐藏下拉列表区
var clear = function () {
$autocomplete.empty().hide();
};
$("#search-text").blur(function () {
//$("#search-text").val("");
});
//注册事件,当输入框失去焦点的时候清空下拉列表并隐藏
$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': cur_danci }, //参数
'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 () {
var $searchInputVal = $searchInput.val();
var $newsearchInputVal = "";
var fenci = findLianci();
selectionStart = selectionEnd = "";
$newsearchInputVal = fenci + term;
$searchInput.val($newsearchInputVal + zhihoudanci);
zhihoudanci = "";
dbClick = false;
//清空并隐藏下拉列表
$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) {
//alert(222);
//setTimeout(ajax_request, 100);
//字母数字,退格,空格
if (event.keyCode > 40 || event.keyCode == 8 || event.keyCode == 32) {
//首先删除下拉列表中的信息
$autocomplete.empty().hide();
clearTimeout(timeoutid);
findLianci();
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键
//findLianci();
if (event.keyCode == 13) {
//列表为空或者鼠标离开导致当前没有索引值
if ($autocomplete.find('li').length == 0 || selectedItem == -1) {
return;
}
//鼠标单击下拉列表的这一项的话,就将这一项的值添加到输入框中
//ciku[ciku.length] = term;
//for (var i = 0; i < ciku.length; i++) {
// lianci = lianci + ciku[i];
//}
//$searchInput.val(lianci);
//清空并隐藏下拉列表
$autocomplete.empty().hide();
// event.preventDefault();
}
})
.keydown(function (event) {
//esc键
if (event.keyCode == 27) {
$autocomplete.empty().hide();
event.preventDefault();
}
}).change(function (event) {
lianci = findLianci();
ajax_request();
}).on("dblclick", function () {
dbClick = true;
getSelectText2("search-text");
//alert("zhihou="+$searchInput.val().substring(selectionEnd))
zhihoudanci = $searchInput.val().substring(selectionEnd);
//alert("start="+selectionStart+"end="+selectionEnd);
}).on("select", function () {
var id = "search-text";
var t = document.getElementById(id);
if (t.selectionStart != undefined && t.selectionEnd != undefined) {
selectionStart = t.selectionStart;
selectionEnd = t.selectionEnd;
}
});
//注册窗口大小改变的事件,重新调整下拉列表的位置
$(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>
<input type="button" id="btn1" name="btn1" value="选择文字" />
<div id="search">
<label for="search-text">请输入关键词</label>
<input type="text" id="search-text" name="search-text" style="width: 40%;" />
<input type="button" id="clear_Content" name="clear_Content" value="清空" />
<input type="button" id="submit" value="搜索" />
</div>
</body>
</html>
2.后台代码
using HraWeb.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace HraWeb
{
public partial class InputAutoCompelete : BasePage
{
// static readonly Regex paramRegex = new Regex(@"^()()$", RegexOptions.Compiled);
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" ,"+", "-", "*", "/","(",")","="};
List<string> opration = new List<string>() { "+", "-", "*", "/" ,"="};
string op = "";
string key = Request["search-text"];
char[] keyChar = key.ToCharArray();
bool hasop = false;
for (int i = 0; i < keyChar.Length; i++)
{
if (opration.Contains(keyChar[i].ToString()))
{
op = keyChar[i].ToString();
keyChar[i] = '|';
hasop = true;
}
}
List<string> jsonList = new List<string>();
List<string> newword = new List<string>();
if (hasop)
{
newword = GetWord(keyChar);
// key = newword[newword.Count - 1];
if (opration.Contains(newword[newword.Count - 1]))
{
jsonList.Add(op);
var json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonList);
HttpContext.Current.Response.Write(json);
HttpContext.Current.Response.End();
}
}
if (!hasop || key.Length == 1)
{
if (key.Length != 0)
{
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();
}
}
}
private List<string> GetWord(char[] keyChar)
{
List<string> newword = new List<string>();
string word = "";
List<string> keyCharList = new List<string>();
keyChar.ToList().ForEach(c =>
{
keyCharList.Add(c.ToString());
});
for (int i = 0; i < keyCharList.Count; i++)
{
string c = keyCharList[i];
if (c != "|")
{
word += c.ToString();
if (i == keyCharList.Count - 1)
{
newword.Add(word);
}
}
else
{
newword.Add(word.TrimEnd('|'));
word = "";
}
}
return newword;
}
}
}
jquery 仿文本编辑器(智能提示输入文字)的更多相关文章
- 【转】仿百度输入框智能提示的js代码
转自:http://www.jb51.net/article/40783.htm 对于我这个JS菜鸟,能找到这样的实属不容易啊!!! 刚开始老大让做这个功能,真是一点头绪都没有,万分感谢!!! 最近客 ...
- 【jQuery】jquery-ui autocomplete智能提示
jQuery UI,简而言之,它是一个基于jQuery的前端UI框架.我们可以使用jQuery + jQuery UI非常简单方便地制作出界面美观.功能强大.跨浏览器兼容的前端html界面. Auto ...
- Eclipse添加Jquery和javascript的智能提示
使用Eclipse写Jquery和Javascript代码的时候,是没有智能提示的.我们可以使用一个插件来解决这个问题. 安装完成后,Eclipse会自动重启.重启之后,我们在项目上右键, 根据自 ...
- 基于bootstrsp的jquery富文本编辑器的手冊说明
重点:当在页面插入文本编辑器后.无法用js/jq的方式去将某些值写入到文本编辑器.如:$("textarea").val("111");$("text ...
- phpstorm编辑器智能提示框架代码
按照上面的步骤就可以智能提示代码了!
- vs Code编辑器智能提示功能
一.Node.Js的Typings工具可以用于Visual Studio Code的代码补全 1.vscode 的默认只有es原声api带有自动补全的功能,现在V1.9的版本默认已经支持NodeJS的 ...
- Visual Studio编辑器“智能提示(IntelliSense)”异常的解决方案
1.删除工程中的 .suo 文件. 2.重启vs
- 使用jQuery实现文本框input定位到文字最后(兼容所有浏览器)
$.fn.setCursorPosition = function(position){ if(this.lengh == 0) return this; return $(this).setSele ...
- 10个免费的javascript富文本编辑器(jQuery and non-jQuery)
祝愿园子里的朋友圣诞节快乐. 本文介绍了10个免费易用富文本编辑器(rich text editors,RTE),其中5个是Jquery插件,另外5个是非Jquery富文本编辑器 简介 Javascr ...
随机推荐
- PhotoShop使用指南(1)——动态图gif的制作
第一步:菜单栏 > 窗口 > 工作区 > 动感 第二步:时间轴 > 设置延迟时间 第三步:时间轴 > 设置循环次数 第四步:存储为Web所用格式 Ctrl+Shift+A ...
- Shiro-从数据表中初始化资源和权限
我们在 applicationContext中配置受保护的资源和权限的关系 <property name="filterChainDefinitions"> <v ...
- 1151 LCA in a Binary Tree(30 分)
The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U ...
- C#异步编程(四)混合模式线程同步
之前讨论了基元用户模式和内核模式线程同步构造.其他所有线程同步构造都基于它们,而且一般都合并了用户模式和内核模式构造,我们称为混合线程同步构造.没有线程竞争时,混合构造提供了基元用户模式构造所具有的性 ...
- 《Orange’s 一个操作系统的实现》1.搭建操作系统开发环境
书中给出了两种环境:windows和linux,平台选择根据自己喜好.本人这里选择ubuntu10.04+virtualbox作为开发平台. 1.下载.安装VirtualBox http:// ...
- hdu 2899 Strange fuction——模拟退火
题目:http://acm.hdu.edu.cn/showproblem.php?pid=2899 还可三分.不过只写了模拟退火. #include<iostream> #include& ...
- xftp连接不上阿里云服务器
打开xftp默认是使用FTP协议,要连接到云服务器,需要将协议改为SFTP 连接成功
- java继承初级
总结:重写方法,方法体内容不同. 还有子类都不能加public.它表示公共,一个程序只能有一个公共类 package com.sa; public class Ac { public void rea ...
- Springboot监控之一:SpringBoot四大神器之Actuator之3-springBoot的监控和管理--指标说明
Spring Boot包含很多其他的特性,它们可以帮你监控和管理发布到生产环境的应用.你可以选择使用HTTP端点,JMX或远程shell(SSH或Telnet)来管理和监控应用.审计(Auditing ...
- 转:MongoDB · 引擎特性 · journal 与 oplog,究竟谁先写入?
转:MongoDB · 引擎特性 · journal 与 oplog,究竟谁先写入? 数据库内核月报 链接:http://mysql.taobao.org/monthly/2018/05/07/ Mo ...