问题
How can I cloze some text in an HTML document? Some marked text is hidden, replaced with an underline of exactly the same length as the original text and all of the words in the sentence should appear in precisely the same places they would appear had there not been a cloze. E.g.:
Once upon a time there ______ a cat.
The word to be clozed might be marked like this:
Once upon a time there <div class="cloze">lived</div> a cat.
Is there some way to hide the text and create an underline of exactly the same length?
回答1:
Use some CSS:
.clozed {
border-bottom:1px solid black;
color:transparent;
}
This is <span class=clozed>text</span>.
Fiddle
回答2:
Adding to @HoboSapiens answer (sorry, I can't comment due to score), you may also want to use the ::selection selector to ensure users can't drag across the area to uncover the text.
http://jsfiddle.net/Delorian/mm8tp1xb/
.clozed::selection {
color: transparent;
}
Note that users will always be able to see the text in the source, so if you want something more effective, you will need to use JavaScript on the client or server-side script to replace the text. However you will lose the benefit of having the underline at an accurate width.
回答3:
You should do it via PHP, because if user would look into source code, he'll see the original text.
But if you need it in JS, you can implement it like this:
var spans = document.querySelectorAll('.clozed');
var words = [];
function repeat (str, count) {
var text = '';
var i;
for (i = 0; i < count; i++) {
text += str;
}
return text;
}
var i, c = spans.length;
for (i = 0; i < c; i++) {
var span = spans[i];
var text = span.innerText = span.textContent;
words.push(text);
span.innerText = span.textContent = repeat('_', text.length);
}
http://jsfiddle.net/0e7hw2a9/
Note: you may use words array to validate the input later.
Update: undo function: http://jsfiddle.net/0e7hw2a9/2/
来源:https://stackoverflow.com/questions/27370638/how-to-create-clozed-text-in-html-css