好的,与此同时,在同事的帮助下,我想出了一个自己的答案来解决这个问题:
<script type="text/javascript">
// holds paragraph A (first selected paragraph)
var a_selected = null;
// holds paragraph B (second selected paragraph)
var b_selected = null;
// holds all 'active' paragraphs
var selected_paras = [];
function class_flipper_init() {
// reset paragraphs A and B
a_selected = null;
b_selected = null;
var paragraphs = $$("#foobar p");
paragraphs.each(function(paragraph, index) {
// if user clicks on a paragraph
paragraph.observe("click", function(event) {
// if A and B are 'active': reset everything.
if(b_selected != null) {
selected_paras.each(function(i) {
toggleStyle(i);
})
a_selected = null
b_selected = null
return
}
// if A is 'active'
if(a_selected != null) {
// if A is 'active' and selected B is below A:
// select all paragraphs between A and B
if(a_selected < index) {
b_selected = index;
for (var i = a_selected + 1; i <= index; i++ ) {
toggleStyle(paragraphs[i])
}
}
// if A is 'active' and selected B is above A:
// select all paragraphs between A and B
else if(a_selected > index) {
b_selected = index;
for (var i = a_selected - 1; i >= index; i-- ) {
toggleStyle(paragraphs[i])
}
}
// if A == B
else {
toggleStyle(paragraph)
a_selected = null
}
}
// if A is selected
else {
a_selected = index;
toggleStyle(paragraph)
}
});
});
}
function toggleStyle(paragraph) {
// remove active class
if (paragraph.hasClassName("active")) {
paragraph.removeClassName("active");
selected_paras = selected_paras.without(paragraph)
}
// set active class
else {
paragraph.addClassName("active");
selected_paras.push(paragraph)
}
}
</script>
class_flipper_init()
每次加载页面(或者在我的情况下是某个部分)时都会调用它。
请不要犹豫,提交用“纯” RJS 或更优雅的方式编写的解决方案。:-)