将指定不透明度的元素淡化为指定的不透明度

将指定不透明度的元素淡化为指定的不透明度

本文介绍了Javascript:将指定不透明度的元素淡化为指定的不透明度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一个可以将元素从指定透明度淡化到指定透明度的函数。例如从0到.7但是我能找到的所有东西都会从0到1或1到0淡化。我找不到任何可以指定从什么到什么的东西。我尝试对我发现的函数进行逆向工程的尝试也失败了,因为我发现的每个例子都非常神秘。

I am trying to find a function that can fade an element from a specified transparency to a specified transparency. For example from 0 to .7 but everything I can find just fades either from 0 to 1 or 1 to 0. I can't find anything that lets you specify from what to what. My attempts of reverse engineering the functions I have found have also failed as every example I have found has been pretty cryptic.

此外,我想在没有任何框架的情况下这样做。

Also I want to do this WITHOUT any frameworks.

谢谢!!

推荐答案

没有特别的技巧,你只需在超时/间隔内将不透明度样式重复设置为0或1以外的值。

There is no particular trick to it, you just set the opacity style to something other than 0 or 1 repeatedly in a timeout/interval.

这是一个可以用作起点的精简淡入淡出函数。 / p>

Here's a stripped down fade function you can use as a starting point.

<script type="text/javascript">
    function fade(element, o0, o1, t) {
        // IE compatibility. Detect lack of native 'opacity' support, and ensure element
        // has layout for IE6-7.
        //
        var canopaque= 'opacity' in element.style;
        if (!canopaque && 'currentStyle' in element && element.currentStyle.hasLayout===false)
            element.style.zoom= '1';

        function setOpacity(o) {
            if (canopaque)
                element.style.opacity= ''+o;
            else
                element.style.filter= 'alpha(opacity='+Math.round(o*100)+')';
        }

        var t0= new Date().getTime();
        setOpacity(o0);
        var interval= setInterval(function() {
            var dt= (new Date().getTime()-t0)/t;
            if (dt>=1) {
                dt= 1;
                clearInterval(interval);
            }
            setOpacity(o1*dt+o0*(1-dt));
        }, 25);
    }
</script>
<p id="foo"> hello. </p>
<button onclick="fade(document.getElementById('foo'), 0.7, 0, 2000);">fade 0.7 to 0</button>

这篇关于Javascript:将指定不透明度的元素淡化为指定的不透明度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 00:29