0

我有以下动画:

<!DOCTYPE HTML>
<html>
<head>
<style>
.example_path {
    position: relative;
    overflow: hidden;
    width: 530px;
    height: 30px;
    border: 3px solid #000;
}

.example_path .example_block {
    position: absolute;
    background-color: blue;
    width: 30px;
    height: 20px;
    padding-top: 10px;
    text-align: center;
    color: #fff;
    font-size: 10px;
    white-space: nowrap;
}
</style>
<script>
function move(elem) {

  var left = 0

  function frame() {

    left+=10  // update parameters 

    elem.style.left = left + 'mm' // show frame 

    if (left == 10000)  // check finish condition
      clearInterval(id)
  }

  var id = setInterval(frame, 1) // draw every 1ms
}
</script>
</head>

<body>
<div onclick="move(this.children[0])" class="example_path">
    <div class="example_block"></div>
</div>
</body>
</html>

如您所见,如果蓝色块越过矩形,它就会移出矩形。我如何让蓝色块围绕矩形边界来回摆动,以保持整个速度恒定......

(在我的情况下,速度是 10 m/s aka 10 mm/ms)

4

2 回答 2

3

您需要将代码更新为:这是工作 JSfiddle

function move(elem) {

        var left = 0
        var fwdMove = true;

        function frame() {
            if (left < 0) {
                fwdMove = true;
            } else if (left > 520) {
                fwdMove = false;
            }

            fwdMove?left += 10:left -= 10
            elem.style.left = left + 'px' // show frame
        }    
        var id = setInterval(frame, 1) // draw every 1ms
    }
于 2013-06-22T16:39:23.503 回答
0

我们首先添加一个变量来跟踪我们前进的方向。我们不想修改您移动的速度,因此我们使用正数或负数 1 来影响位置。

var direction = 1; // 1=Right, -1=Left
var left = 0

function frame() {
    left+=(10 * direction);  // update parameters 

因为 mm 是一个打印单元,而且我们在浏览器中工作,所以我们将其更改为使用 px。如果您确实需要使用 mm,则必须找到一种在它们之间进行转换的方法,以使框停在适当的位置。

elem.style.left = left + 'px' // show frame 

最后,我们检查是否超出了盒子的边界,如果是,我们将它放回盒子中并反转方向;

if (left <= 0) {
    direction = 1; // Begin moving to the left
    left = 0; // Put the box back in the path
} else if (left >= (530 - 20)) {
    direction = -1; // Begin moving to the right
    left = (530 - 20); // Put the box back in the path
}

JSF中。

于 2013-06-22T16:43:19.803 回答