问题
I'd like an input field that I can have javascript set certain attributes for, for different parts of the input field. A simple example to demonstrate what I'd like to do: let's say I want to underline all curse words in an input text area. So the javascript would check the input text area when a new letter is inserted, and for any words matching my array of recognized curse words, it would underline the word. Note, I do not want the user/client to be able to set any attributes of the text, I simply want the javascript to be able to format certain words differently than others (so, no toolbars or anything like that). I also want the box to look exactly like a regular text area in every other regard.
I'm already aware of some rich text editors (like juju editor and lwrte) as well as some syntax highlighters but I'm not sure if they do what I want.
So, anyone know of a tool that would let me do this?
Thanks
回答1:
You can make a div "contenteditable" by setting that attribute to true on the div. Then surround the words in question with markup that doesn't affect layout, but that can be styled and easily removed later.
Something like this:
<style type="text/css">
.content {
border: 5px inset #000;
padding: 5px;
}
.content .curse {
color: #f00;
font-weight: bold;
text-decoration: underline;
}
</style>
<div contentEditable="true" class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean consequat gravida tempus. Vivamus convallis, purus dictum bibendum ullamcorper, neque ipsum aliquam ligula, sit amet imperdiet est ante non nisl. Mauris dignissim libero et urna iaculis at iaculis metus semper. Sed ac nisl eu arcu molestie pretium quis quis ligula. Cras vitae enim vitae lacus molestie dictum. Donec rutrum tincidunt augue, vel pretium lectus faucibus ut. In consequat diam accumsan urna fermentum vitae tincidunt ipsum rutrum. Curabitur sagittis, ante a viverra fringilla, orci urna feugiat urna, eu ultricies lacus odio adipiscing risus. Sed pellentesque blandit ipsum vel hendrerit. Nulla nibh mauris, egestas sed consectetur et, lobortis in dolor. Curabitur eu ante lectus. Cras consequat, dui sed pellentesque tempor, purus turpis egestas sapien, in fermentum eros tortor vel mi. Integer accumsan, augue id elementum pretium, est quam vehicula nisl, at congue purus sem quis ipsum. Aliquam commodo, erat in euismod lacinia, tortor lectus interdum lacus, quis vestibulum augue nulla in tellus.
</div>
<script type="text/javascript">
$(document).ready(function() {
var html = $('.content').html();
$('.content').html(html.replace(/lectus/gi, '<span class="curse">lectus</span>'));
});
</script>
来源:https://stackoverflow.com/questions/3613184/how-can-i-create-an-html-input-text-area-such-that-i-can-underline-or-format-cer