我有一个CSS元素/球,单击时将移至新坐标。
[此方法有效,但是我正在应用的过渡方法似乎并未生效。
球跳到新位置。但我希望它缓慢地动画/过渡/移动到新坐标。
我在做什么错?
.ball {
width: 30px;
height: 30px;
border-radius: 50%;
background-color: #FF5722;
position: absolute;
// d.style.transition = "all 1s ease-in";
transition: all 3s ease-in-out;
// -webkit-transition: all 1s ease-in-out;
// -moz-transition: all 1s ease-in-out;
// -o-transition: all 1s ease-in-out;
// -ms-transition: all 1s ease-in-out;
}
handleClick = (e) => {
console.log('ball clicked');
var d = document.getElementById('ball');
console.log('d', d);
d.style.x = 12 + "px";
d.style.top = 341 + "px";
d.style.transition = "all 1s ease-in";
}
谢谢
似乎有些事情需要纠正;
.ball
类设置样式,其中通过id访问ball元素,这表明存在潜在的问题。是否将ball
类应用于ID为ball
的元素?x
属性应替换为left
属性,以确保球形元素的水平移动这是演示这些更正的示例:
const handleClick = (e) => {
console.log('ball clicked');
const ball = document.getElementById('ball');
/* Setting random coordinates to demonstrate transition */
ball.style.left = Number.parseInt(Math.random() * 200) + "px";
ball.style.top = Number.parseInt(Math.random() * 200) + "px";
}
document.addEventListener("click", handleClick);
#field {
position: relative;
width: 100%;
height: 100%;
}
/* Corrected to id selector with # rather than class selector
with . */
#ball {
position: absolute;
width: 30px;
height: 30px;
border-radius: 50%;
background-color: #FF5722;
position: absolute;
/* Assigning transition behavior which is applied during
property changes */
transition: all 3s ease-in-out;
}
<div id="field">
<div id="ball"></div>
</div>
希望有所帮助
您必须为x
和top
分配默认值,否则您将尝试从无内容过渡。
P.S。看来您的CSS选择的是CLASS为ball
的元素,而不是ID为ball
的元素。在CSS中使用#ball
代替.ball
。 (归功于jaromanda-x)
window.onclick = (e) => {
console.log('ball clicked');
var d = document.getElementById('ball');
console.log('d', d);
d.style.x = 12 + "px";
d.style.top = 341 + "px";
d.style.transition = "all 1s ease-in";
}
#ball {
width: 30px;
height: 30px;
border-radius: 50%;
background-color: #FF5722;
position: absolute;
// d.style.transition = "all 1s ease-in";
transition: all 3s ease-in-out;
// -webkit-transition: all 1s ease-in-out;
// -moz-transition: all 1s ease-in-out;
// -o-transition: all 1s ease-in-out;
// -ms-transition: all 1s ease-in-out;
x:0; /* default value */
top:0; /* default value */
}
<div id="ball">
为了使过渡正常工作,您需要先在样式中定义它,然后将其从JavaScript中删除。
查看此:
handleClick = (e) => {
console.log('ball clicked');
var d = document.getElementById('ball');
console.log('d', d);
d.style.x = 12 + "px";
d.style.top = 341 + "px";
}
#ball {
width: 30px;
height: 30px;
border-radius: 50%;
background-color: #FF5722;
position: absolute;
top: 0;
left: 0;
transition: all 3s ease-in-out;
}
<div id="ball" onclick="handleClick()"></div>