Demo 1
A rather ugly little solution, compounded by the fact that it is 3:30 in the morning. However, it works with text blocks and allows each individual line individually.
Fiddle: http://jsfiddle.net/Fptq2/2/
Chrome 26, FF 20, Safari 5.1.7, IE 8/9/10 (perhaps it could be made functional)
Essentially this:
- Divides the source into separate words once
- Wraps every word in between (ugly but effective - any style can now be applied to a range)
- Uses a simple position calculation to determine if an item is lower than the previous one.
- Changes colors based on index change
- # 3-5 ( !)
$(".stripe").each(function(){
var obj = $(this);
var html = obj.html().replace(/(\S+\s*)/g, "<span>$1</span>");
obj.html(html);
});
function highlight(){
var offset = 0;
var colorIndex = 0;
var colors = ["#eee","#000"];
var spans = $(".stripe span");
for(var i = 0; i < spans.length; i++){
var newOffset = spans[i].offsetTop;
if(newOffset !== offset){
colorIndex = colorIndex === 0 ? 1 : 0;
offset = newOffset;
}
spans[i].style.color = colors[colorIndex];
}
}
highlight();
$(window).on("resize", highlight);
2
Fiddle: http://jsfiddle.net/Fptq2/4/
(function () {
$(".stripe").each(function () {
var obj = $(this);
var html = obj.html().replace(/(\S+\s*)/g, "<span>$1</span>");
obj.html(html);
});
var offset = 0;
var colorIndex = 0;
var colors = ["#ccc", "#000"];
var spans = $(".stripe span");
function highlight() {
for (var i = 0; i < spans.length; i++) {
var newOffset = spans[i].offsetTop;
if (newOffset !== offset) {
colorIndex = colorIndex === 0 ? 1 : 0;
offset = newOffset;
}
spans[i].style.color = colors[colorIndex];
}
}
highlight();
var timeout;
function throttle(){
window.clearTimeout(timeout);
timeout = window.setTimeout(highlight, 100);
}
$(window).on("resize", throttle);
})();
