我是JavaScript中的新手,我正在尝试编写一个代码,在我熟悉的命令中淡入图片。我在这里看过几个例子,但是他们没有工作。这就是我试图做的事情:
function myFunction() {
for (i = 1; i < 20; i++) {
setTimeout(function() {
o = 1 - 1 / i
}, 200); //this should increase the opacity
document.getElementById("dog").style.opacity = o
}
}
&#13;
img {
opacity: 0;
filter: alpha(opacity=40);
}
&#13;
<center>
<img id="dog" src="dog.jpg" draggable="true" ondragstart="drag(event)" width="500" height="500">
</center>
<button onclick="myFunction()">Lets Rock</button>
&#13;
当我运行它时,它不会淡入。它以空白屏幕开始(应该如此),但是在点击按钮后它不会消失,而是弹出(不会淡入)点击几下。
非常感谢你给予的帮助 爱丽儿
答案 0 :(得分:3)
试试这个:http://jsfiddle.net/kishoresahas/4wg8zcsg/
function fadeIn(el) {
el.style.opacity = 0;
var tick = function () {
el.style.opacity = +el.style.opacity + 0.01;
if (+el.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
}
};
tick();
}
function myFunction() {
var el = document.getElementById("dog");
console.log(el);
fadeIn(el);
}
&#13;
img {
opacity: 0;
filter: alpha(opacity=40);
}
&#13;
<button onclick="myFunction()">Lets Rock</button>
<center>
<img id="dog" src="dog.jpg" draggable="true" ondragstart="drag(event)" width="500" height="500">
</center>
&#13;
答案 1 :(得分:1)
您可能会发现使用CSS控制不透明度更容易。它对浏览器的工作较少,只需要最少的javascript来切换课程。
var img = document.getElementById("dog"),
btn = document.getElementById("button");
btn.addEventListener("click", function( event ) {
img.className = (img.className==="in")?"out":"in";
}, false);
#dog {
opacity: 0;
-webkit-transition: opacity 2s ease;
-moz-transition: opacity 2s ease;
-ms-transition: opacity 2s ease;
-o-transition: opacity 2s ease;
transition: opacity 2s ease;
}
#dog.in {
opacity: 1;
}
<button id="button">Lets Rock</button><br />
<img id="dog" src="http://lorempixel.com/500/500/cats/" class="off" draggable="true" ondragstart="drag(event)" width="500" height="500">