为什么字符串在一定间隔内不移动



我正在尝试制作一个简单的代码,每 1 毫秒移动 20 像素的行(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>

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

//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>

  • line必须是定位absolute元素,以便left CSS 属性将影响
  • 我假设您在interval中分配left属性时没有提到+px(unit)因为element.offsetWidth不会返回带有值的unit[Ref]
这是我

的镜头:

<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>

相关内容

  • 没有找到相关文章

最新更新