本节代码主要使用了 onmousedown 事件和 event.button 属性,主要功能和用法如下。
• settimeout 方法,在执行时是在载入后延迟指定时间后,去执行一次表达式,仅执行一次。
• charat 方法返回一个字符值,该字符位于指定索引位置。字符串中的第一个字符的索引为0,第二个的索引为1,等等。超出有效范围的索引值返回空字符串。
var layers = document.layers;
var style = document.all;
var both = layers || style;
var idme = 908601;
if(layers) //如果不是ie浏览器
{
layerref = 'document.layers';
styleref = '';
}
if(style) //如果是ie浏览器
{
layerref = 'document.all';
styleref = '.style';
}
function writeontext(obj, str) { //函数在页面上打印字符串
if(layers) {
with(document[obj]) {
document.open();
document.write(str); //write方法打印字符串
document.close();
}
}
if(style) eval(obj+'.innerhtml = str'); //使用innerhtml属性显示字符串
}
var dispstr = new array("-www.jb51.net"); //字符串数组
var overme = 0;
function txttyper(str, idx, idobj, spobj, clr1,clr2, delay, plysnd) //函数:实现打字效果
{
var tmp0 = tmp1 = '', skip = 100;
if(both && idx <= str.length) {
if(str.charat(idx) == '') idx++;
idx++;
}
if(str.charat(idx) == '&' && str.charat(idx+1) != '') {
while(str.charat(idx) != ';') idx++;
idx++;
}
tmp0 = str.slice(0, idx);
tmp1 = str.charat(idx++);
if(overme==0 && plysnd==1) {
if(navigator.plugins[0]) {
if(navigator.plugins["liveaudio"][0].type == "audio/basic" && navigator.javaenabled()) {
document.embeds[0].stop();
settimeout("document.embeds[0].play(false)", 100);
}
} else if(document.all) {
ding.stop();
settimeout("ding.run()", 100);
}
overme = 1;
} else {
overme = 0;
}
writeontext(idobj, ""+tmp0+""+tmp1+"");
//调用writeontext函数将字符显示在网页上
settimeout("txttyper('"+str+"', "+idx+", '"+idobj+"', '"+spobj+"', '"+clr1+"', '"+clr2+"', "+delay+", "+plysnd+")", delay);
}
}
function init()
{
txttyper(dispstr[0], 0, 'tt10', 'ttll', '#339933', '#99ff33', 300, 0); //调用txttyper函数开始打字
}
打字效果的文字特效
[ctrl+a 全选 注:如需引入外部js需刷新才能执行]
运行该程序后,页面出现一个提示信息,然后逐个出现字符。如此逐个出现字符后,等待全部打印完毕即可停止打印。
源程序解读
(1)程序首先建立了一个层,其 id 为 ttl0,便于以后调用。这个层用来显示打印的文字。
(2)程序在<body>元素上添加 onload 事件,当整个页面载入完成以后,该事件被触发,调用 init() 事件处理函数,对该事件进行处理。
(3)在函数 txttyper() 中,使用 charat 方法得到字符串中的某个字符。使用 if 条件语句判断该字符是否满足尽头。满足条件后打印在页面上。
(4)在 if 语句中,也可使用任意合法的 javascript 语句,完成更为复杂的操作。