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, hier nun die Variante mit CSS Transitions.
fade in fade out move left move right
HTML
cssAnimate.htm HTML (438 Bytes) 26.10.2021 22:55
<!DOCTYPE html >
<html lang = "en" >
<head >
<meta charset = "utf-8" />
<title > Simple CSS Transition 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 = "cssAnimate.js" > </script >
</body >
</html >
StyleSheet
cssAnimate.js JavaScript (1,97 kByte) 26.10.2021 22:13
(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 cssAnimate(name, value) {
var attr = name, to = value;
el.style.transition = attr + " 0.5s ease" ;
if (name == 'opacity' ) {
setOpacity(el, to);
} else {
el.style.setProperty(attr, to + "px" );
}
var transitionend = function () {
el.style.transition = "none" ;
};
setTimeout(function (){ transitionend(); }, 500 );
}
var fadeIn = document .getElementById( 'fadeIn' );
if (fadeIn) {
fadeIn.addEventListener('click' , function () {
cssAnimate('opacity' , '1' );
});
}
var fadeOut = document .getElementById( 'fadeOut' );
if (fadeOut) {
fadeOut.addEventListener('click' , function () {
cssAnimate('opacity' , '0' );
});
}
var moveLeft = document .getElementById( 'moveLeft' );
if (moveLeft) {
moveLeft.addEventListener('click' , function () {
cssAnimate('left' , '0' );
});
}
var moveRight = document .getElementById( 'moveRight' );
if (moveRight) {
moveRight.addEventListener('click' , function () {
cssAnimate('left' , wrapper.offsetWidth- 100 );
});
}
})();