Skip to content

Instantly share code, notes, and snippets.

@codeachange
Created September 30, 2013 06:32
Show Gist options
  • Save codeachange/6760039 to your computer and use it in GitHub Desktop.
Save codeachange/6760039 to your computer and use it in GitHub Desktop.
屏幕键盘未完成版
// 屏幕键盘
$(".keyhd").mousedown(function(){
$(this).addClass("active");
}).mouseup(function(){
var keyvalue = $(this).text();
var target = current_input_target.get(0);
if(target){
if(/^[0-9a-zA-Z]$/.test(keyvalue)){
insertAtCursor(target,keyvalue);
}else{
if($(this).hasClass("backspace")){
backspaceAtCursor(target);
}else if($(this).hasClass("delete")){
deleteAtCursor(target);
}else if($(this).hasClass("reset")){
current_input_target.val("");
}
}
// stupid autocomplete won't work without this event fired
if(target.id == "skeyword"){
current_input_target.keydown();
}
}
}).mouseout(function(){
$(".keyhd.active").removeClass("active");
});
$(document).mouseup(function(){
$(".keyhd.active").removeClass("active");
});
function insertAtCursor(obj,str){
if (document.selection){
$(obj).focus();
var sel = document.selection.createRange();
sel.text = str;
}else if(typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number'){
var startPos = obj.selectionStart,
endPos = obj.selectionEnd,
cursorPos = startPos,
tmpStr = obj.value;
obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);
cursorPos += str.length;
obj.selectionStart = obj.selectionEnd = cursorPos;
}
}
function backspaceAtCursor(obj){
if(document.selection){
$(obj).focus();
var range = document.selection.createRange();
range.moveStart("character",-1);
range.select();
document.selection.clear();
}else if(typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number' ){
var startPos = obj.selectionStart,
endPos = obj.selectionEnd,
cursorPos = startPos,
tmpStr = obj.value;
obj.value = tmpStr.substring(0, startPos-1) + tmpStr.substring(endPos, tmpStr.length);
cursorPos -= 1;
obj.selectionStart = obj.selectionEnd = cursorPos;
}
}
function deleteAtCursor(obj){
if(document.selection){
$(obj).focus();
/* var range = document.selection.createRange();
range.moveEnd("character",1);
range.select();
在没有选择任何东西的情况下,selection.clear() 删除光标后面的一个字符 */
document.selection.clear();
}else if(typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number' ){
var startPos = obj.selectionStart,
endPos = obj.selectionEnd,
cursorPos = startPos,
tmpStr = obj.value;
obj.value = tmpStr.substring(0, startPos) + tmpStr.substring(endPos+1, tmpStr.length);
obj.selectionStart = obj.selectionEnd = cursorPos;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment