use*_*231 6 html javascript opacity
我是 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
}
}Run Code Online (Sandbox Code Playgroud)
img {
opacity: 0;
filter: alpha(opacity=40);
}Run Code Online (Sandbox Code Playgroud)
<center>
<img id="dog" src="dog.jpg" draggable="true" ondragstart="drag(event)" width="500" height="500">
</center>
<button onclick="myFunction()">Lets Rock</button>Run Code Online (Sandbox Code Playgroud)
当我运行它时,它不会淡入。它以空白屏幕开始(正如它应该的那样),但不是在我单击按钮后淡入,而是在单击几次后弹出(不淡入)。
非常感谢你给予
Ariel的帮助
试试这个: 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);
}Run Code Online (Sandbox Code Playgroud)
img {
opacity: 0;
filter: alpha(opacity=40);
}Run Code Online (Sandbox Code Playgroud)
<button onclick="myFunction()">Lets Rock</button>
<center>
<img id="dog" src="https://i.stack.imgur.com/NHlV8.jpg" draggable="true" ondragstart="drag(event)" width="500" height="500">
</center>Run Code Online (Sandbox Code Playgroud)
您可能会发现使用 CSS 控制不透明度更容易。它对浏览器的工作量较少,并且只需要最少的 JavaScript 来切换类。
var img = document.getElementById("dog"),
btn = document.getElementById("button");
btn.addEventListener("click", function( event ) {
img.className = (img.className==="in")?"out":"in";
}, false);Run Code Online (Sandbox Code Playgroud)
#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;
}Run Code Online (Sandbox Code Playgroud)
<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">Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13152 次 |
| 最近记录: |