I want to have a textarea which displays line numbers on the left. Wrap should be set to "off" (so that horizontal scrolling is available). I want to have my page as a single self-contained .html file (there will be no graphics), so I'd like to avoid any 3rd party frameworks.
Which way should I go? How would you开发者_Python百科 do this?
I would start with two text-areas and synchronzation mechanism. Something like this,
<script>
window.sync = function(e){
var textarea = document.getElementById("lines");
var source = document.getElementById("some_text_area");
textarea.scrollTop = source.scrollTop;
}
window.populate = function populate(){
if(populate.started){
return;
}
populate.started = true;
var textarea = document.getElementById("lines");
var str = '';
for(var i=0;i < 100;i++){
str = str + (i +'\r\n');
}
textarea.value = str;
}
</script>
<div>
<textarea
style="width:40px;overflow:hidden;height:40px;"
readonly="true"
id="lines"
></textarea>
<textarea
style="width:500px;height:40px;"
id="some_text_area"
onclick="populate()"
onscroll="sync();"
></textarea>
</div>
Ofcourse populate()
function (and the style declaration and event declaration) should be more robust and intelligent, , but, it just for showcase purpose.
I think your best bet would be to just have a regular textarea, and show a preview (like stack overflow) as they type along. Within that preview, you could easily add line numbers on each line and format the look via CSS.
Another simple method is to create a narrow, but tall background image and some left padding on the textarea. This has the minor caveat of having a fixed number of rows and font style, but it is the option with the least amount of code required.
Without images, that's a tough one.
Best bet: Place a second textarea with identical settings (font size, line height, padding...) but different styling (no background color, no borders) to the left of your original textarea. Make it read only, take it out of the tab rotation (tabindex=99999
might do the trick or simply disabling it), and put line numbers in it. This should work well and correctly as far as I can think, it should even survive things like the client resizing the font manually in their browser.
You could even use position: relative
and a big padding-left:
value in the original textarea to move the counter textarea into the original one.
Downside: The line counter won't follow vertical scrolling of the textarea. See the comments below.
You'd have to wrap the text area and capture the keystrokes looking for newline characters (Eg ENTER). Doing a quick Google search and you get http://www.dhtmlgoodies.com/forum/viewtopic.php?t=506
Personally I'd just have a regular textarea and a div down the left side that displays the numbers (possibly auto-adjusting as more carriage returns get added to it).
精彩评论