如何使隐藏/显示文本javascript更流畅?

时间:2013-07-07 12:16:51

标签: javascript html

我正在使用此脚本来隐藏和显示文本但是,我希望过渡更顺畅,但我不知道如何。以下是它的演示:http://jsfiddle.net/LnE5U/

请帮助我改变它以使其更顺畅。

<a href="javascript:showOrHide();">hide/show text</a>
<div id="showOrHideDiv" style="display: none">hidden text</div>


<script language="javascript">
    function showOrHide() 
    {
        var div = document.getElementById("showOrHideDiv");
        if (div.style.display == "block") 
        {
            div.style.display = "none";
        }
        else 
        {
            div.style.display = "block";
        }
    } 
</script>

5 个答案:

答案 0 :(得分:3)

以下是使用 jQuery fadeToggle的示例(更复杂的animate的快捷方式)

// assuming jQuery
$(function () {                      // on document ready
    var div = $('#showOrHideDiv');   // cache <div>
    $('#action').click(function () { // on click on the `<a>`
        div.fadeToggle(1000);        // toggle div visibility over 1 second
    });
});

HTML

<a id="action" href="#">hide/show text</a>
<div id="showOrHideDiv" style="display: none;">hidden text</div>

DEMO


JavaScript 推子的示例。它看起来很复杂,因为我写它是为了支持改变方向和持续时间。不过,我确信仍然可以对它进行改进。

function generateFader(elem) {
    var t = null, goal, current = 0, inProgress = 0;
    if (!elem || elem.nodeType !== 1) throw new TypeError('Expecting input of Element');
    function visible(e) {
        var s = window.getComputedStyle(e);
        return +!(s.display === 'none' || s.opacity === '0');
    }
    function fader(duration) {
        var step, aStep, fn, thisID = ++current, vis = visible(elem);
        window.clearTimeout(t);
        if (inProgress) goal = 1 - goal; // reverse direction if there is one running
        else goal = 1 - vis;             // else decide direction
        if (goal) {                      // make sure visibility settings correct if hidden
            if (!vis) elem.style.opacity = '0';
            elem.style.display = 'block';
        }
        step = goal - +window.getComputedStyle(elem).opacity;
        step = 20 * step / duration;     // calculate how much to change by every 20ms
        if (step >= 0) {                 // prevent rounding issues
            if (step < 0.0001) step = 0.0001;
        } else if (step > -0.0001) step = -0.0001;
        aStep = Math.abs(step);          // cache
        fn = function () {
            // console.log(step, goal, thisID, current); // debug here
            var o = +window.getComputedStyle(elem).opacity;
            if (thisID !== current) return;
            if (Math.abs(goal - o) < aStep) {            // finished
                elem.style.opacity = goal;
                if (!goal) elem.style.display = 'none';
                inProgress = 0;
                return;
            }
            elem.style.opacity = (o + step).toFixed(5);
            t = window.setTimeout(fn, 20);
        }
        inProgress = 1; // mark started
        fn();           // start
    }
    return fader;
}

使用它

window.addEventListener( // this section matches the code above
    'load',
    function () {
        var fader = generateFader(document.getElementById('showOrHideDiv'));
        document.getElementById('action').addEventListener(
            'click',
            function () {
                fader(1000);
            }
        );
    }
);

DEMO of this

答案 1 :(得分:1)

  

这很简单。我刚刚做了一个演示,我使用了setInterval

     

以下是它的工作原理

var fadeout = function( element ) { // 1
    element.style.opacity = 1; // 2
    window.setInterval(function() { // 3
        if(element.style.opacity > 0) { // 4
            element.style.opacity = parseFloat(element.style.opacity - 0.01).toFixed(2); // 5 
        } else {
            element.style.display = 'none'; // 6 
        }
    }, 50);
};

JSFiddle Demo Link

  

步骤

     
      
  1. 创建一个接受DOM元素的函数
  2.   
  3. 将元素的不透明度设置为1
  4.   
  5. 创建一个每50ms循环的函数
  6.   
  7. 如果不透明度大于0 - >继续
  8.   
  9. 从不透明度中取走0.01
  10.   
  11. 如果小于0则动画完成并完全隐藏
  12.   

请注意,这是一个非常简单的示例,需要做一些工作

答案 2 :(得分:0)

你可以使用这样的东西

    $('.showOrHideDiv').toggle(function() {
      $('showOrHideDiv').fadeIn('slow', function() {
        //fadeIn or fadeOut, slow or fast, all the stuffs you want to trigger, "a function to execute every odd time the element is clicked," says the  [jquery doc][1]
        });
    }, function() {
        //here comes "additional handlers to cycle through after clicks," says the [jquery doc][1]
    });

答案 3 :(得分:0)

我遵循了 iConnor 解决方案并且工作正常,但它有一个小问题 setInterval 在元素被隐藏后不会停止我添加了停止间隔以提高性能

var fadeout = function( element ) { // 1
    element.style.opacity = 1; // 2
    let hidden_process = window.setInterval(function() { // 3
        if(element.style.opacity > 0) { // 4
            element.style.opacity = parseFloat(element.style.opacity - 0.01).toFixed(2); // 5 
        } else {
            element.style.display = 'none'; // 6 
            console.log('1');
            clearInterval(hidden_process);
        }
    }, 50);
    
    
};

答案 4 :(得分:-1)

使用OPACITY 使其显示/隐藏。请参阅此示例,完整代码(不带jQuery):

<a href="javascript:ShowDiv('MyMesage');"> Click here</a>

<div id="MyMesage" style="display:none; background-color:pink; margin:0 0 0 100px;width:200px;">
blablabla
</div>

<script>
function ShowDiv(name){
    //duration of transition (1000 miliseconds equals 1 second)
    var duration = 1000;
    // how many times should it should be changed in delay duration
    var AmountOfActions=100;

    var diiv= document.getElementById(name);
    diiv.style.opacity = '0';   diiv.style.display = 'block';   var counte=0;
    setInterval(function(){counte ++;
       if ( counte<AmountOfActions) { diiv.style.opacity = counte/AmountOfActions;}
    },
    duration / AmountOfActions);
}
</script>