Native js implementation fadein and fadeout fadeout effect

  • 2020-03-30 03:09:49
  • OfStack

Js set inside the DOM node function attributes of transparency: filter = "alpha (opacity =" + value + ") "(compatible with Internet explorer) and opacity = value / 100 (compatible with FF and GG).

Let's start with the transparency compatibility code:
 
function setOpacity(ele, opacity) { 
if (ele.style.opacity != undefined) { 
/// compatible with FF and GG and new versions of IE
ele.style.opacity = opacity / 100; 

} else { 
/// compatible with older versions of ie
ele.style.filter = "alpha(opacity=" + opacity + ")"; 
} 
} 

About some friends:
 
function setOpacity(ele, opacity) { 
if (document.all) { 
/// compatible with ie
ele.style.filter = "alpha(opacity=" + opacity + ")"; 
} 
ele { 
/// compatible with FF and GG
ele.style.opacity = opacity / 100; 
} 
} 

I would like to say that there is a problem with this running under IE10, there is no response after the click. Because consumer support opacity attribute does not support the filter, this method is not desirable.

Fadein function code:
 
function fadein(ele, opacity, speed) { 
if (ele) { 
var v = ele.style.filter.replace("alpha(opacity=", "").replace(")", "") || ele.style.opacity; 
v < 1 && (v = v * 100); 
var count = speed / 1000; 
var avg = count < 2 ? (opacity / count) : (opacity / count - 1); 
var timer = null; 
timer = setInterval(function() { 
if (v < opacity) { 
v += avg; 
setOpacity(ele, v); 
} else { 
clearInterval(timer); 
} 
}, 500); 
} 
} 

Fadeout function code:
 
function fadeout(ele, opacity, speed) { 
if (ele) { 
var v = ele.style.filter.replace("alpha(opacity=", "").replace(")", "") || ele.style.opacity || 100; 
v < 1 && (v = v * 100); 
var count = speed / 1000; 
var avg = (100 - opacity) / count; 
var timer = null; 
timer = setInterval(function() { 
if (v - avg > opacity) { 
v -= avg; 
setOpacity(ele, v); 
} else { 
clearInterval(timer); 
} 
}, 500); 
} 
} 

Here is a demo example:
 
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title></title> 
<script type="text/javascript" src="fade.js"></script> 
<script type="text/javascript"> 

window.onload = function () { 


document.getElementById('Button1').onclick = function () { 

fadeout(document.getElementById('DV'), 0, 6000); 

} 
document.getElementById('Button2').onclick = function () { 

fadein(document.getElementById('DV'), 80, 6000); 

} 
} 
</script> 
</head> 
<body> 

<div id="DV" style="background-color: green; width: 400px; height: 400px;"></div> 
<input id="Button1" type="button" value="button" /> 
<input id="Button2" type="button" value="button" /> 

</body> 
</html> 

What is a better way to achieve the message...

Related articles: