Sicherlich gibt es einige fertige Routinen um eine Animation (slide, resize, ...) zu erzielen, z.B. jQuery .animate() aber manchmal reicht auch die kleine Lösung.
HTML
<!DOCTYPE html >
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Simple Animate Example</title>
</head>
<body><button id="fadeIn">fade in</button><button id="fadeOut">fade out</button><button id="moveLeft">move left</button><button id="moveRight">move right</button>
<div id="wrapper">
<div id="el"></div>
</div>
<script src="animate.js"></script>
</body>
</html>
StyleSheet
// coding: utf-8
/** Created by: Udo Schmal | https://www.gocher.me/ */
(function () {
'use strict';
var el = document.getElementById('el'),
wrapper = document.getElementById('wrapper');
wrapper.style.position = 'relative';
wrapper.style.height = '105px';
wrapper.style.width = '100%';
el.style.position = 'absolute';
el.style.left = '150px';
el.style.top = '0';
el.style.display = 'block';
el.style.backgroundColor = 'silver';
el.style.border = '1px solid red';
el.style.width = '100px';
el.style.height = '100px';
function getOpacity(def) {
var result;
var style=document.defaultView.getComputedStyle(el, null);
if ('opacity' in style) {
result = style.opacity;
}
result = parseInt(result);
if (!isNaN(result)) result = def;
return result;
}
function setOpacity(el, val) {
el.style.opacity = val;
}
function animateBox(attr, dest, callback) {
var from, attribute = attr, to = dest, fc = callback;
if (attribute == 'opacity') {
from = parseInt(getOpacity(to == '0' ? '1' : '0'));
} else {
if (el.style.getPropertyValue) {
from = parseInt(el.style.getPropertyValue(attribute));
} else {
from = parseInt(el.style.getAttribute(attribute));
}
};
if (from == to) return;
var start = Date.now();
var output = document.getElementById('output');
var tick = function() {
var t = Math.min(1, ((Date.now() - start) / 1000));
var eased = t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1;
var val = (eased * (to - from)) + from;
if (attribute == 'opacity') {
setOpacity(el, val);
} else {
if (el.style.setProperty) {
el.style.setProperty(attribute, val + "px");
} else {
el.style.setAttribute(attribute, val + "px");
}
};
if (t<1) {
window.requestAnimationFrame(tick);
} else {
if (fc) fc();
}
};
tick();
}
var fadeIn = document.getElementById('fadeIn');
if (fadeIn) {
fadeIn.addEventListener('click', function () {
animateBox('opacity', '1');
});
}
var fadeOut = document.getElementById('fadeOut');
if (fadeOut) {
fadeOut.addEventListener('click', function () {
animateBox('opacity', '0');
});
}
var moveLeft = document.getElementById('moveLeft');
if (moveLeft) {
moveLeft.addEventListener('click', function () {
animateBox('left', '0');
});
}
var moveRight = document.getElementById('moveRight');
if (moveRight) {
moveRight.addEventListener('click', function () {
animateBox('left', wrapper.offsetWidth-100);
});
}
})();