我有以下动画:

<!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,即10 mm / ms)

最佳答案

您需要将代码更新为:Here is working 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
    }

10-08 17:01