自己写了一个文字的水平滚动的效果.JS代码如下:
var tag = 0; //若不设置为全局变量,不会左移
function wordflow(id,minflow,maxflow){
var OText = document.getElementById(id)||document.getElementsByClassName(id)[0];
// alert(typeof(OText));
var currentLeft = parseInt(window.getComputedStyle(OText,null).left)||parseInt(OText.style.left);
console.log(currentLeft);
//右移
if(currentLeft<maxflow &&tag==0){
currentLeft++;
if (currentLeft==maxflow) {
tag = 1;
}
}
//左移
if(currentLeft>minflow &&tag==1)
{
currentLeft--;
if (currentLeft==minflow) {
tag =0;
}
}
OText.style.left = currentLeft + "px";
// console.log(OText.style.left);
var timer = setTimeout(wordflow(id,minflow,maxflow),30);
};
window.οnlοad=function(){
wordflow('words',200,500);
console.log("123");
};
CSS部分:
#words{
position:absolute;
left:200px;
top:100px;
font-family:'宋体';
font-size:30px;
color:red;
overflow:hidden;
}
HTML部分:
<body>
<div id = "words" > 今天的天气虽然下雨,但心情还是不错哦!</div>
</body>
运行完成之后发现报错如下图所示
经过查阅资料后,发现setTimeout需要传入函数指针,所以将setTimeout此段代码更改如下:
wordflow.bind(null,id,minflow,maxflow) 采用函数时间绑定的方式.运行之后发现文字能按预期的水平循环滚动.