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

ab_non 发布于 2019-08-14 javascript 最后更新 2019-08-14 08:39 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>
已邀请:

eomnis

赞同来自:

  • line必须是absolute定位元素,以便left css属性影响
  • 我假设您在left中分配PLACEHOLDER_FOR_CODE_4属性时未提及+px(unit),因为element.offsetWidth未返回值为[Ref]
  • unit

ererum

赞同来自:

看看下面的示例,它有一些评论可以帮助您理解,结帐演示和玩代码

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

cnon

赞同来自:

这是我的镜头:

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