Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

setInterval的问题

html结构

    <ul>
        <ul id="x">li*20</ul>
        <ul>li*20</ul>
    </ul>

中间的2个ul内容完全相同,外部ul默认显示10个li,overflow:hidden.
效果就是每X秒向上滚动1次,刷新一个新的li出来.滚动的过程持续1s,滚动一次的距离是70px.起初想法是100ms7px 但是移动效果稍显卡顿,遂改成 50ms 3.5px ,但因为有了小数点的关系,margin-top的值就变得不可控,几次循环之后会出现比如-283px这种数值(本该是-280px)
下面是js代码:

function move(){
            var _count = 0
            var list = document.getElementById("x");
            var mtop = window.getComputedStyle(list).marginTop;
            mtop = parseInt(mtop);
            mtop <= -1400? mtop=0:mtop=mtop;
            function setp(){
                _count ++
                mtop = mtop - 3.5;
                mt = mtop + "px"
                list.style.marginTop = mt;
                if(_count==20){clearInterval(timer);}
            }
            var timer = setInterval(setp,50);
        }
    setInterval(move,3000)

现在发现问题并不是出在浮点数上,而是setIntetval函数,当焦点一直在当前页面时,是不会出错了,切换到别的页面,过一段时间再切回来,就会出错.
有一个相似的问题:https://segmentfault.com/q/10...
但是我想寻求兼容IE8+,通过原生JS解决的办法.谢谢!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

不要累加,每次都计数乘以单条高度呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...