你的位置:首页 > 软件开发 > Java > 对js操作html的实践【2】——随机标题与滚动标题

对js操作html的实践【2】——随机标题与滚动标题

发布时间:2017-08-17 21:00:21
先放几张今天要达成的效果图(随机标题效果)(滚动标题效果)接下来放出源码:1.随机标题1 //指定条目数2 tips = new Array(1);3 //条目内容4 tips[0] = '很抱歉冒险就是从来不会让人做好准备。';5 tips[1] = ' ...

对js操作html的实践【2】——随机标题与滚动标题

先放几张今天要达成的效果图

对js操作html的实践【2】——随机标题与滚动标题

对js操作html的实践【2】——随机标题与滚动标题

随机标题效果)

对js操作html的实践【2】——随机标题与滚动标题

(滚动标题效果)

接下来放出源码:

1.随机标题

1 //指定条目数2 tips = new Array(1);3 //条目内容4 tips[0] = '很抱歉冒险就是从来不会让人做好准备。';5 tips[1] = 'Let us start!';6 index = Math.floor(Math.random() * tips.length);7 window.document.title += "平行世界 The Parallel Universe - "+tips[index];

(1)在上面的源码中,用到了随机数运算,取随机数的实现可以达成非常多的随机特效:

取随机数有以下几种方法:

1.Math.random(); 结果为0-1间的一个随机数(包括0,不包括1) 
2.Math.floor(num); 参数num为一个数值,函数结果为num的整数部分。 
3.Math.round(num); 参数num为一个数值,函数结果为num四舍五入后的整数。

Math:数学对象,提供对数据的数学计算。
Math.random(); 返回0和1间(包括0,不包括1)的一个随机数。

Math.ceil(n); 返回大于等于n的最小整数。
用Math.ceil(Math.random()*10);时,主要获取1到10的随机整数,取0的几率极小。

Math.round(n); 返回n四舍五入后整数的值。
用Math.round(Math.random());可均衡获取0到1的随机整数。
用Math.round(Math.random()*10);时,可基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。

Math.floor(n); 返回小于等于n的最大整数。
用Math.floor(Math.random()*10);时,可均衡获取0到9的随机整数。

(参考自互联网

(2)是的如果我想加入更多随机用量,可以这样写代码:

1 //指定条目数2 tips = new Array(4);3 //条目内容4 tips[0] = '很抱歉冒险就是从来不会让人做好准备。';5 tips[1] = 'Let us start!';6 tips[2] = 'QAQ';7 tips[3] = 'BBQ';8 index = Math.floor(Math.random() * tips.length);9 window.document.title += "平行世界 The Parallel Universe - "+tips[index];

这之中用到了数组(tips)许多编程语言都相通,数组的元素是从0开始的

对js操作html的实践【2】——随机标题与滚动标题||对js操作html的实践【2】——随机标题与滚动标题

代码很简单,在此不再赘述。

2.滚动标题。以下是代码:

 1 var repeat=0 //enter 0 to not repeat scrolling after 1 run, othersise, enter 1 2 var title=document.title 3 var leng=title.length 4 var start=1 5 function titlemove() { 6 titl=title.substring(start, leng) + title.substring(0, start) 7 document.title=titl 8 start++ 9 if (start==leng+1) {10  start=011  if (repeat==0)12  return13  }14 setTimeout("titlemove()",240)15 }16 if (document.title)17 titlemove()

这个代码也很容易理解,只要弄清楚原理与.substring的用法:源码中利用substring截取了起始位置(start)到末尾的所有字符。

并将从0开始到start位置的字符加到其末尾,不断更新达到滚动效果。

总结:随机数、数组等在js中有很大的用处,但还是看创新,我相信想到就能做到!

 

原标题:对js操作html的实践【2】——随机标题与滚动标题

关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。