imuncle.github.io
imuncle.github.io copied to clipboard
一个动态的浪漫小程序
trafficstars
今天翻到了一个有趣的小玩意儿,也体现了程序员的浪漫,可惜的是这位程序员在两天前分手了。
原地址在这里:Love-Gift
页面演示在这里:idealclover
第一眼看到就被惊艳到了,确实很用心!于是我赶紧下载下来研究了一下源代码。
这个项目参考了pen#pwlxxp项目,基本思想是动态改变网页的style标签和body内容。关键代码如下:
(function() {
var codeTime, commentTime, finalStyle, isOn, openComment, skip, styles, writeStyleChar, writeStyles;
styles = "将要展示的style样式,也就是页面动态显示的内容"
openComment = false;
isOn = true;
writeStyleChar = function(which) {
if (which === '/' && openComment === false) {
openComment = true;
styles = $('#style-text').html() + which;
} else if (which === '/' && openComment === true) {
openComment = false;
styles = $('#style-text').html().replace(/(\/[^\/]*\*)$/, '<em class="comment">$1/</em>');
} else if (which === ':') {
styles = $('#style-text').html().replace(/([a-zA-Z- ^\n]*)$/, '<em class="key">$1</em>:');
} else if (which === ';') {
styles = $('#style-text').html().replace(/([^:]*)$/, '<em class="value">$1</em>;');
} else if (which === '{') {
styles = $('#style-text').html().replace(/(.*)$/, '<em class="selector">$1</em>{');
} else {
styles = $('#style-text').html() + which;
}
$('#style-text').html(styles);
return $('#style-tag').append(which);
};
writeStyles = function(message, index, interval) {
var pre;
if (index < message.length) {
pre = document.getElementById('style-text');
pre.scrollTop = pre.scrollHeight;
writeStyleChar(message[index++]);
if (isOn) {
return setTimeout((function() {
return writeStyles(message, index, openComment ? commentTime : codeTime);
}), interval);
}
}
};
skip = function() {
isOn = false;
return setTimeout((function() {
var pre;
$('#style-text').html(finalStyle);
$('#style-tag').html(finalStyle);
pre = document.getElementById('style-text');
return pre.scrollTop = pre.scrollHeight;
}), 2 * commentTime);
};
commentTime = 60;
codeTime = 20;
writeStyles(styles, 0, commentTime);
}).call(this);
把想要展示的文字内容写在style中,然后定期执行writeStyles函数,周期为codeTime或commentTime,这取决于是不是在显示“注释”。
writeStyles函数中又调用了writeStyleChar函数。这个函数逐个字节扫描style字符串,通过判断是否是斜杠、花括号、冒号、分号等来判断当前显示的是注释、代码块、属性、属性值等,进而分配对应的class类,用于代码高亮显示。
writeStyles函数负责改变HTML的style标签,writeStyleChar函数负责改变HTML的pre标签,也就是我们看到的动态打字效果。至于其他的页面样式变动,红心的出现,则是由动态改变的style控制。
真的太有趣了!