JS文字滚动效果
没什么技术难度,主要是Array对象的push()和shift()方法的调用。
一般的实现方法,即直接分别在id为start和stop的button上添加onclick事件,然后执行相应的函数:
html:
<div id="test">这里是滚动的文字!</div> <p class="btns"><button type="button" id="start">开始</button><button type="button" id="stop">结束</button></p>
实现方法:
function $(id) {
return document.getElementById(id);
};
window.onload = function() {
var t = null;
$("start").onclick = function() {
clearInterval(t);
var s = $('test').innerText.split('');
t = setInterval(function() {
s.push(s.shift());//滚动
$('test').innerText = s.join('');
}, 300);
$("start").disabled = true;//单击开始按钮后禁用开始按钮
$("stop").disabled = false;//单击开始按钮后启用结束按钮
};
$("stop").onclick = function() {
clearInterval(t);//清除间歇调用
$("start").disabled = false;
$("stop").disabled = true;
};
}
另外再使用面向对象的编程方法,主要考虑可扩展性:
function $(id) {
return document.getElementById(id);
};
function ScrollText(text, fn, time) {
this.text = text.split('');
this.fn = fn;
this.time = time || 300;
}
ScrollText.prototype.start = function() {
var s = this.text;
var fn = this.fn;
clearInterval(this.interval);
this.interval = setInterval(function() {
s.push(s.shift());
fn(s.join(""));//这个函数是处理传进来的字符串的,指定将它作为某个对象的文本
}, this.time);
};
ScrollText.prototype.stop = function() {
clearInterval(this.interval);
};
window.onload = function() {
var txt = $("test").innerHTML;
var scrollText = new ScrollText(txt, function(t) {
$("test").innerHTML = t;
});
/*var txt = $("test").innerHTML;
var scrollText = new ScrollText(txt, function(t) {
document.title = t;
});*/
$("start").onclick = function() {
scrollText.start();
$("start").disabled = true;//单击开始按钮后禁用开始按钮
$("stop").disabled = false;//单击开始按钮后启用结束按钮
};
$("stop").onclick = function() {
scrollText.stop();
$("start").disabled = false;
$("stop").disabled = true;
};
}
进行扩展后,可以对任意的文本设置滚动。
浙公网安备 33010602011771号