Coz i have not earned 10 reputations that i cannot post image here, please click here to see my example textarea. There is no ENTER at the end of the first line and is there any solution to know at which character it turns to next line? Take this for instance, it turns to next line after the character "哪" or after the 13th character. (SBC case or DBC case characters can be inputed.)
views:
73answers:
3Well, when you create a textarea you are supposed to supply the number of columns, so if it's wrapping because it's reached the end of the line, it seems fair to assume that the number of characters is the number of columns you have specified. Or am I missing something?
The cols
attribute determines the width of the textarea
element but is usually overridden by a stylesheet and the width
property. Even without a width set by CSS, cols
is not strictly enforced by most browsers (in Chrome at least it is accurate as long as the vertical scrollbar is present), and besides lines are usually wrapped at word boundaries not character.
Here's an ugly solution but it should work. The idea is to set the height of the textarea element to 0 then remove words from the end of its value string one at a time, and check the scrollHeight
property for changes.
//make scrollbars take up space even when they are not needed
//necessary to keep space available for text constant
txtarea.style.overflow = 'scroll !important';
txtarea.style.height = '0px !important';
var tmpvalue = txtarea.value;
var currentscroll = txtarea.scrollHeight;
var wrapat = [];
var parts;
//Regex breaks textarea value into ['every word but the last', 'one']
while (parts = txtarea.value.match(/([^\0]*)\s\w*/m)) {
txtarea.value = parts[1];
//scrollHeight has changed, add wrap index to array
if (txtarea.scrollHeight < currentscroll) {
wrapat.push(txtarea.value.length-1);
currentscroll = txtarea.scrollHeight;
}
}
//sort wrap array for niceness
wrapat = wrapat.sort(function(a,b) { return a-b; });
//restore everything to normal
txtarea.value = tmpvalue;
txtarea.style.height = '';`
Try the code out here http://jsbin.com/alasa3/edit
There are probably bugs, for instance this code does not handle long "words" such as URL's that might get broken in two. Also it takes a little extra computation to determine if a line was wrapped automaticly or because of a newline (somewhat dealt with in code from link), and it might have trouble with words seperated by multiple spaces/newlines. But that's the basic idea.
If there is an easier solution I'm not aware of it.