我使用Javascript通过转换从画布中心到左上角的圆圈进行翻译。我接下来要做的是调用一个函数,在画布中选择随机坐标并将它们发送到translate,这样它的位置就可以移动了。不幸的是,这不起作用。
你能在CSS中的元素上调用一次翻译吗?这是我要来的结论,但我还没有能够在文档中找到信息,说这种行为不允许
。问题的核心:
function change_level() {
var level = document.getElementById("level");
level.parentNode.removeChild(level);
var ball = document.getElementById("init_pos");
ball.style.backgroundColor = "orange";
ball.style.borderRadius = "25px";
ball.style.transform = "translate(-600%, -647%)";
setTimeout(ball_movement(ball), 3000);
ball.style.transition = "background-color 2s ease-in, transform 3s ease";
}
function ball_movement(ball) {
var movements = 5;
var x;
var y;
for (var i = 0; i < movements; i++) {
x = getRandomArbitrary(-800, 800);
y = getRandomArbitrary(-800, 800);
ball.style.transform = "translate("+x+", "+y+")";
ball.style.transition = "transform 3s ease";
console.log(x);
}
}
在jsfiddle上发布我的代码,虽然我的计算比jsfiddle中的校园大,所以不能正常工作。
答案 0 :(得分:3)
您的代码需要进行一些更正:
transform
内设置ball_movement
值时,x
和y
变量仅包含数字作为值,但translate
函数需要具有单位的值(百分比,像素等)。因此,请根据需要将px
或%
附加到字符串中来添加。timeout
函数调用中,当您将第一个参数设为ball_movement(ball)
时,会立即调用该函数。你应该把它包装在一个匿名函数中。 注意:在下面的代码段中,我减少了translate
函数的初始值和随机数计算的输入,以保持球在边界内移动。
window.onload = function() {
var
html_display = {
0: "Level One",
1: "Level Two",
2: "Level Three",
3: "Level Four",
4: "Level Five"
};
html_key = 0;
//need to take level offscreen, add ball
function change_level() {
var level = document.getElementById("level");
level.parentNode.removeChild(level);
var ball = document.getElementById("init_pos");
ball.style.backgroundColor = "orange";
ball.style.borderRadius = "25px";
ball.style.transform = "translate(-150%, -150%)";
ball.style.transition = "background-color 2s ease-in, transform 3s ease";
setTimeout(function() {
ball_movement(ball);
}, 3000);
}
function ball_movement(ball) {
var movements = 5;
var x;
var y;
for (var i = 0; i < movements; i++) {
x = getRandomArbitrary(-100, 100);
y = getRandomArbitrary(-100, 100);
ball.style.transform = "translate(" + x + "px, " + y + "px)";
ball.style.transition = "transform 3s ease";
}
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
function intro_html() {
document.getElementById("level").innerHTML = html_display[html_key];
setTimeout(change_level, 1000);
}
intro_html();
}
body {
position: absolute;
top: 45%;
left: 50%;
-moz-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
}
#level {
font-family: helvetica;
font-size: 29px;
position: absolute;
top: 45%;
left: 50%;
-moz-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
}
#init_pos {
position: absolute;
top: 44%;
left: 48.17%;
height: 50px;
width: 50px;
}
.container {
height: 700px;
width: 1100px;
top: 45%;
left: 50%;
border: 4px solid black;
overflow: hidden;
}
<div class="container">
<p id="level"></p>
<p id="init_pos"></p>
</div>