Line Number Enhancements for HTML Textarea
Question: How can line numbers be displayed in the left margin of a
Answer:
Introducing CodeMirror
Highly recommended by members of the community is CodeMirror, a powerful tool that excels in displaying line numbers.
Implementation
CodeMirror offers effortless integration. Incorporate it into your project by implementing the following code:
var editor = CodeMirror.fromTextArea(document.getElementById('code'), { lineNumbers: true, mode: 'text/x-perl', theme: 'abbott', });
In this example:
Demo
Experience a fully functional demonstration of CodeMirror with line numbers within the StackOverflow sandbox:
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/mode/perl/perl.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/theme/abbott.min.css"> <textarea>
Additional Considerations
Other solutions may encounter issues with line number alignment. This is often due to monitor DPI settings that are not accounted for. However, CodeMirror handles these situations effectively.
The above is the detailed content of How to Add Line Numbers to an HTML Textarea?. For more information, please follow other related articles on the PHP Chinese website!