Is it possible to create a new element with javascript and add it to body, then automatically animate it with css? This is my test page

<body>

<script>
function menuMain(){
    Title = document.createElement("div");
    Title.style.left = "750px";
    Title.style.webkitTransition = "4s";
    Title.style.fontSize = "30px";
    Title.style.position = "fixed";
    Title.style.color = "red";
    Title.id = "titleid";
    Title.innerHTML = "Menu Title";
    document.getElementsByTagName("body")[0].appendChild(Title);
    Title.style.left = "200px";
}

menuMain();
</script>

</body>

But it just automatically places the object at left:200px, instead of animating it from 750px to 200px. I know Title.style.webkitTransition = "4s" works because when I inspect element it's there in the element's style

I also tried replacing

Title.style.left = "200px";

with

document.getElementById("titleid").style.left = "200px";

but it just does the same thing.

I know when I create the element manually, then change left with javascript it animated from left:750px to left:200px

<body>
<div id="titleid" style="-webkit-transition:4s;position:absolute;color:red;font-size:30px;left:750px;">Menu Title</div>
<script>
function menuMain(){
    document.getElementById("titleid").style.left = "200px";
}

menuMain();
</script>

</body>

but this is not what I want to do. So is it possibly somehow?

有帮助吗?

解决方案

Assuming you just want a transition, take a look at jQuery animation: http://api.jquery.com/animate/

It will make something like this trivial.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top