使用原始javascript淡化HTML元素 [英] Fade HTML element with raw javascript

查看:135
本文介绍了使用原始javascript淡化HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我与同一问题相关的第二个问题,所以我为此道歉。

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:

鉴于我有一个像这样的div:

Given I have a "div" like so:

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

我用来淡出它的JavaScript函数是:

The JavaScript function that I'm using to fade it out is:

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);

有人可以看看这个,让我知道我做错了什么,我只想要要做的是FADE IN一个不透明度等于1的元素。

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".

顺便说一下,我不能使用jQuery,但我渴望这样学习。

By the way, I can't use jQuery, however I'm eager to learn this way.

谢谢

我试图扭转这个功能如下:

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在全局范围内运行,所以你需要定义相对于窗口的计时器。

setInterval runs in a global scope, so you need to define the timer relative to the window.

你不能连接从style属性返回的字符串值,
期望一个数字 - 你会得到' 0.02.02.02.02'

You can't concatinate the string value returned from the style property and expect a number- you'll get '0.02.02.02.02'

强制字符串中的数字,然后添加.02。

Coerce a number out of the string, then add the .02.

它可以在某些浏览器中使用,但是在9之前的IE需要一个不同的表达式
来设置和读取不透明度。

It will work in some browsers, but IE before 9 needs a different expression to set and read opacity.

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);
}

这篇关于使用原始javascript淡化HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆