简体   繁体   English

使用原始javascript淡化HTML元素

[英]Fade HTML element with raw javascript

It's my second question of the day related to the same problem, so I apologize for that. 这是我与同一问题有关的第二个问题,所以我为此道歉。

I was able to put together a function to "fade out" an element, and it works just fine, my problem is that when I try to reverse it, so the element "fades in" it does not work. 我能够组合一个功能来“淡出”一个元素,它工作得很好,我的问题是当我试图反转它时,所以元素“淡入”它不起作用。 I've tried to change the obvious, but I can't understand what I'm doing wrong. 我试图改变明显的,但我无法理解我做错了什么。

My code so far is as follows: 我的代码到目前为止如下:

Given I have a "div" like so: 鉴于我有一个像这样的“div”:

<div id="test" style="width:200px; height:200px; display:block; opacity:1; background-color:red;"></div>

The JavaScript function that I'm using to fade it out is: 我用来淡出它的JavaScript函数是:

var getElement = document.getElementById('test');
function fadeOut(elem, speed){
if(!elem.style.opacity){
    elem.style.opacity = 1;
}
var desvanecer = setInterval(function(){
    elem.style.opacity -= .02;
    if(elem.style.opacity < 0){
        clearInterval(desvanecer);
    }
}, speed / 50);
}
fadeOut(getElement, 500);

Could somebody take a look at this and let me know what I'm doing wrong, all I want to do is "FADE IN" an element to an opacity equal to "1". 有人可以看看这个,让我知道我做错了什么,我想做的就是“FADE IN”一个不透明度等于“1”的元素。

By the way, I can't use jQuery, however I'm eager to learn this way. 顺便说一句,我不能使用jQuery,但我渴望以这种方式学习。

Thanks 谢谢

My attemp to reverse the function is as follows: 我试图扭转这个功能如下:

var getElement = document.getElementById('test');
function fadeIn(elem, speed){
if(elem.style.opacity){
    elem.style.opacity = 0;
}
var desvanecer = setInterval(function(){
    elem.style.opacity += .02;
    if(elem.style.opacity > 1){
        clearInterval(desvanecer);
    }
}, speed / 50); 
}
fadeIn(getElement, 500);

setInterval runs in a global scope, so you need to define the timer relative to the window. setInterval在全局范围内运行,因此您需要相对于窗口定义计时器。

You can't concatinate the string value returned from the style property and expect a number- you'll get '0.02.02.02.02' 你不能连接从style属性返回的字符串值并期望一个数字 - 你会得到'0.02.02.02.02'

Coerce a number out of the string, then add the .02. 强制字符串中的数字,然后添加.02。

It will work in some browsers, but IE before 9 needs a different expression to set and read opacity. 它适用于某些浏览器,但9之前的IE需要不同的表达式来设置和读取不透明度。

function fadeIn(elem, speed){
    if(elem.style){
        elem.style.opacity= '0';
    }
    window.fadetimer= setInterval(function(){
        elem.style.opacity= +(elem.style.opacity)+.02;
        if(elem.style.opacity> 1){
            clearInterval(fadetimer);
        }
    },
    speed);
}

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

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