Issues related to transparency Settings in native js and jquery

  • 2020-03-30 01:18:21
  • OfStack

In the daily development of the website, often used to set the transparency problem, the simplest is the picture of the fade in effect. Here are some of the issues and points to note about setting transparency in native js and jQuery:

1. Transparency style setting
Transparency is set differently in IE than in other related browsers. IE USES the filter: alpha attribute, firefox USES the opactiy attribute, and the following example sets transparency to 30% :
IE: filter: alpha (opacity: 30);
Firefox: opacity (0.3);

2 native js setting transparency
In order to be compatible with the transparency Settings of Internet explorer and other browsers, we need to set the above two styles separately.

 
var alpha = 30; //Transparency value variable
var oDiv = document.getElementById('div1'); //Gets the DOM element object
oDiv.style.filter = 'alpha(opacity:'+alpha+')'; //Set the transparency of IE
oDiv.style.opacity = alpha / 100; //Set the opacity such as fierfox to a decimal value

JQuery sets transparency
JQuery has integrated the setting of transparency, which is compatible with Internet explorer and other browsers. You can modify the opactiy attribute value, which is a decimal value, so you only need to set it once.
 
$(function(){ 
$("#div1").css("opacity","0.3"); //Set transparency
}); 

4 an example
The example USES native js to fade in and out of a div. The mouse moves into div area, the transparency is 100%, the mouse moves out div area the transparency is 30%, at the same time USES the time to control the transparency conversion effect;
 
window.onload=function() 
{ 
var oDiv = document.getElementById('div1');//Gets the DOM object of the div
oDiv.onmouseover = function() //Mouse over method
{ 
startMove(100); 
}; 
oDiv.onmouseout = function() //Mouse out method
{ 
startMove(30); 
}; 
} 

var timer = null;//Time object
var alpha = 30;//Initial transparency value
function startMove(iTarget) 
{ 
var oDiv = document.getElementById('div1'); 
clearInterval(timer);// empty Time object
timer = setInterval(function(){ 
var speed = 0; 
if(alpha < iTarget) 
{ 
speed =5; 
} 
else 
{ 
speed = -5; 
} 

if(alpha == iTarget) 
{ 
clearInterval(timer); 
} 
else 
{ 
alpha +=speed; //Transparency value increases the effect
oDiv.style.filter = 'alpha(opacity:'+alpha+')'; //Set IE transparency
oDiv.style.opacity = alpha / 100; //Set other browsers
} 
},30); 
} 


Related articles: