简体   繁体   English

如何使用for循环更改图像的不透明度以创建逐渐照亮的效果?

[英]How do I change the opacity of an image using a for loop to create a gradual lighting up effect?

I have created a Css class which defines the opacity of my image but I need to access it in JavaScript and change it in a for loop then pass the new opacity back to a variable and repeat the process until I have the opacity I want which is 100%. 我创建了一个Css类,该类定义了图像的不透明度,但是我需要在JavaScript中访问它,并在for循环中对其进行更改,然后将新的不透明度传递给变量,然后重复该过程,直到获得所需的不透明度为止100%。

I need this to be triggered by the onmouseover event handler. 我需要由onmouseover事件处理程序触发。 Can anyone show me some code so I know how its done? 谁能给我看一些代码,让我知道它是如何完成的?

css in my external stylesheet: 我的外部样式表中的CSS:

.test{

opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
}
// assuming jQuery
$('.test').bind({
 mouseover: function() {
  $(this).animate({opacity:1},500,function(){
    // something to do when done
  });
 }
});

Using straight forward javascript, you'll want to get the element: 使用简单的javascript,您将需要获取元素:

var element = this;// for example or var element = document.getElementById('some-id');

var opacity = element.style.opacity;

function updateOpacity() {
  opacity = opacity+=0.2;
  if(opacity >= 1) {
    // done
    opacity = 1;
  } else {
    element.style.opacity = opacity; // this updates the opacity
    setTimeout(function(){updateOpacity();}, 50); // 50 is the delay, 50milliseconds
  }
}

Quick Note from the comments: 快速注释:

The setTimeout() call can be used in the following ways: 可以通过以下方式使用setTimeout()调用:

  1. if you have NO parameters to pass, use this 如果您没有要传递的参数,请使用此

    setTimeout(updateOpacity, 50); setTimeout(updateOpacity,50);

  2. if you are working with legacy code, you may find this, which works, but see below 如果您使用的是旧版代码,则可能会找到合适的方法,但请参见下文

    setTimeout("updateOpacity();", 50); setTimeout(“ updateOpacity();”,50);

  3. if you need to pass parameters to your callback function, use this in preference to 2. 如果您需要将参数传递给回调函数,请优先使用2。

    setTimeout(function(){ updateOpacity(); }, 50); setTimeout(function(){updateOpacity();},50);

With jQuery you can use 使用jQuery,您可以使用

$('.test').fadeTo( 500, 1.0 ); //fade to 100% opaque in 500 ms

Ref: http://api.jquery.com/fadeTo/ 参考: http : //api.jquery.com/fadeTo/

For on mouseover: 对于鼠标悬停:

$('.test').mouseover(function(){
  $(this).fadeTo( 500, 1.0 );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM