4

我正在使用这个脚本来隐藏和显示文本,但是我想让过渡更平滑,但我不知道该怎么做。这是一个演示: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>
4

5 回答 5

4

这是一个使用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>

演示


纯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

于 2013-07-07T12:38:25.097 回答
2

这很简单。我刚刚做了一个演示,我使用了 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 演示链接

脚步

  1. 创建一个接受 DOM 元素的函数
  2. 将元素的不透明度设置为 1
  3. 创建一个每 50 毫秒循环一次的函数
  4. 如果不透明度大于 0 -> 继续
  5. 从不透明度中去掉 0.01
  6. 如果小于 0 则动画完成并完全隐藏

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

于 2013-07-07T12:36:01.243 回答
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]
    });
于 2013-07-07T12:49:29.310 回答
0

使用 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>
于 2014-01-22T15:22:42.633 回答
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);
    
    
};
于 2021-04-09T22:50:39.290 回答