1

我正在尝试制作一个每 20 毫秒移动 1px 的行的简单代码(smt 就像一个股票行情)。此外,希望它使用 .offsetWidth 属性到达浏览器窗口的边缘后消失。不幸的是,我被卡住了,我不知道为什么它根本不动。请帮我找出错误,还是我走错了方向?谢谢!

<html>
<head>
    <title>Blablabla</title>
    <meta charset ="utf-8">
    <!-- <script type="text/javascript" src="line.js"></script> -->
</head>
<body onload="interval()">
    <div id="line">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    </div>
<script type="text/javascript">
    function interval() {
        var line = setInterval(function(){document.getElementById("line").style.left = scroll.offsetWidth}, 20);
    }
</script>
</body>
</html>
4

3 回答 3

0
  • line必须absolute定位元素,以便leftcss 属性会影响
  • +px(unit)我假设您在分配left属性时没有提到intervalaselement.offsetWidth不返回unit值 [ Ref ]
于 2016-02-16T10:24:26.350 回答
0

看看下面的示例,它的注释应该可以帮助您理解、查看演示和玩弄代码

//set starting offset
var leftOffset = 0;

//assign element to variable
var element = document.getElementById("line");

//css.left requires position.absolute
element.style.position = 'absolute';

//calculate width of element, in display.block it's 100%
element.style.display = 'inline-block';

//assign interval id to a variable for cancelation
var interval = setInterval(function(){
  
  //increase offset by 1
  leftOffset = leftOffset + 1;

  //check if element is sticked  to screen.right
  if(leftOffset + element.offsetWidth < document.body.offsetWidth) {
    //not sticked
    
    //add pixels
    element.style.left = leftOffset + 'px';
  } else {
    //sticked

    //remove interval
    clearInterval(interval);
    
    //hide element
    element.style.display = 'none';
  }
}, 20);
<div id="line">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
</div>

于 2016-02-16T10:28:58.157 回答
0

这是我的镜头:

<html>
<head>
    <title>Blablabla</title>
    <meta charset ="utf-8">
    <!-- <script type="text/javascript" src="line.js"></script> -->
</head>
<body>
    <div id="line">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    </div>
<script type="text/javascript">
number = 5; //should be increased each time
setInterval(function(){var d = document.getElementById('line');
d.style.position = "absolute";
number++; //increase number
d.style.left = number; //move the div according to the number
}, 200); //notice that you can increase/decrease 200 according to your will

</script>
</body>
</html>
于 2016-02-16T10:34:48.760 回答