js method to achieve transparency gradient effect

  • 2020-05-26 07:52:37
  • OfStack

This article demonstrates an example of how js can achieve transparency gradients. Share with you for your reference. The specific analysis is as follows:

Here you can implement 1 and the transparency of the element is 30 at the beginning, and as you mouse over it, the transparency slowly increases, and you stop at 100. Mouse out, transparency slowly decreased, reduced to 30 effect.

Point 1: since you cannot directly obtain and change the transparency value, you can assign the transparency value to a variable, let the variable change, and finally assign the value of the variable to the transparency value of the element.


var alpha=30;

Point 2: judge the target value and the current transparent value to determine whether the velocity is positive or negative.


if(target > alpha){
speed = 2;
}else{
speed = -2;
}

Point 3: if the transparency value reaches the target value, turn off the timer, otherwise the transparency value continues to change. Finally, assign the value to the element, and because transparency is incompatible, you need to write it in two ways.


if(alpha == target){
clearInterval(timer);
}
else{
alpha = alpha + speed;
run.style.filter = 'alpha(opacity='+alpha+')';
run.style.opacity = alpha/100;
document.title = alpha;
}

Finally, add the code:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title> Headless document </title>
<style>
body{margin:0; padding:0;}
#run{width:100px; height:100px; background:#06c;
position:absolute; border:1px solid #000;
opacity:0.3; filter:alpha(opacity=30);}
</style>
<script>
window.onload = function(){
 var run = document.getElementById("run");
 var btn = document.getElementById("btn");
 var speed = 1;
 var timer = null;
 var alpha=30;
 run.onmouseover = function(){
  startrun(100);
 }
 run.onmouseout = function(){
  startrun(30);
 }
 function startrun(target){
  clearInterval(timer);
  timer = setInterval(function(){
   if(target > alpha){
    speed = 2;
   }else{
    speed = -2;
   }
   if(alpha == target){
    clearInterval(timer);
   }
   else{
    alpha = alpha + speed;
    run.style.filter = 'alpha(opacity='+alpha+')';
    run.style.opacity = alpha/100;
    document.title = alpha;
   }
  },30)
 }
}
</script>
</head>
<body>
<div id="run"></div>
</body>
</html>

I hope this article has helped you with your javascript programming.


Related articles: