This article mainly introduces the method of JS movement to change the transparency of a single object, and analyzes the JS operation skills related to dynamic modification of page element attributes in the form of examples. Friends who are interested in JavaScript can refer to this article. Article
In addition to changing the width, height, letf, top position or movement direction of the object to achieve the movement effect of the object, changing the transparency of the object is also a special movement effect
<script> window.onload = function () { var op = document.getElementById('p1'); op.onmousemove = function () { startMove(100); } op.onmouseout = function () { startMove(30); } } var timer = null; function startMove(iTarget) { clearInterval(timer); var op = document.getElementById('p1'); timer = setInterval(function(){ if(op.offsetAlpha == iTarget){ .... } },30); } </script>
But in js There are only four methods, offsetLeft/Top and offsetWidth/Height, but there is no offsetAlpha method.
Question: So how do we get the transparency of the current object? ?
We can define a variable var alpha = 30; by judging whether this variable is equal to the target value, we can continue our next operation;
var alpha = 30; // 自定义一个变量
When alpha is equal to the target value, ClearTimer, otherwise change the transparency value alpha
if(alpha == iTarget){ clearInterval(timer); }else{ alpha += iSpeed; op.style.opacity = alpha/100; op.style.filter = 'alpha(opacity:'+alpha+')'; }
The complete code is as follows:
<p id="p1"></p>
css style part:
<style> #p1{ width: 100px;height: 100px; background: green; opacity:0.3; filter:alpha(opacity:30);/*兼容低版本IE*/ } </style>
js part:
<script> window.onload = function () { var op = document.getElementById('p1'); op.onmousemove = function () { startMove(100); } op.onmouseout = function () { startMove(30); } } var timer = null; var alpha = 30; function startMove(iTarget) { clearInterval(timer); var op = document.getElementById('p1'); var iSpeed = 0; timer = setInterval(function(){ if(alpha>iTarget){ iSpeed = -10; }else{ iSpeed = 10; } if(alpha == iTarget){ clearInterval(timer); }else{ alpha += iSpeed; op.style.opacity = alpha/100; op.style.filter = 'alpha(opacity:'+alpha+')'; } },30); } </script>
The above is all the content of this article, I hope it can help everyone learn! !
Related recommendations:
js is encapsulated into a plug-in_Canvas statistical chart plug-in writing example
html, css, javascript to achieve floor jumping Page layout
#Detailed explanation of JavaScript module mode
The above is the detailed content of Analysis of the method of changing the transparency of a single object with JS motion. For more information, please follow other related articles on the PHP Chinese website!