jQuery val() not working with Caret logic in Chrome
I'm working with an in开发者_如何学JAVAput field which I've mapped keyCodes for so that a keyboard input will render a different language character into the input field.
The problem becomes when the characters reach the end of the input 'view' any additional input for "mapped" characters which are using the jQuery val() method will not be interpreted as a key input from the browser hence keeping the last inputted character always visible.
So I have to add caret logic (bottom input in jsfiddle uses the caret logic) but this doesn't work on Chrome/(webkit?)
Here is a jsfiddle of my example. http://jsfiddle.net/dwickwire/S9EKN/
EDIT: I tested with the following versions, works in FF but not in Chrome for me
Mac Snow Leapord OSX 10.6.7
Chrome: v 11.0.696.68, v 11.0.696.71 - don't work
Firefox: 4.0.1 - works
Windows Chrome: -v unsure - doesn't work
I'm unsure of how I can resolve this, any ideas? Thanks
If you save and add to the scrollLeft
position of the input, it will update and keep the typed character in view. Although, it fails if you click and start typing in the middle of the input.
I updated the second input demo with the code below. Also note that the input and test span that is added should have the same font size.
input_2.bind('keydown.keyboard', function(e) {
var key = "",
current_val = input_2.val(),
pos = input_2.caret(),
start_pos = pos.start,
end_pos = pos.end,
scroll = $(this).scrollLeft();
// some mapped keys
switch (e.which) {
// e key
case 69:
key = "ε";
e.preventDefault();
break;
// f key
case 70:
key = "φ";
e.preventDefault();
break;
// z key
case 90:
key = "ζ";
e.preventDefault();
break;
// a key
case 65:
key = "α";
e.preventDefault();
break;
}
if (key !== '') {
var test = $('<span class="test"> ' + key + '</span>').appendTo('body');
scroll += test.width();
test.remove();
}
input_2.val(current_val + key);
//Insert/Replace text at caret then restore caret
input_2.value = current_val.substr(0, start_pos) + key + current_val.substr(end_pos, current_val.length);
input_2.caret(start_pos + key.length, start_pos + key.length);
if (key !== '') {
$(this).scrollLeft(scroll);
}
});
Update: the scrollLeft position seemed to be a bit off, so if you add a
inside the span with the character, it works out much better (updated demo)
精彩评论