如何在此javascript

时间:2016-01-15 00:03:09

标签: javascript fade effect

我想知道如何在此javascript代码切换上添加淡入淡出效果。

//<![CDATA[
function toggleList(id, displayValue) {
    var obj = document.getElementById(id);
    if(!displayValue)
    {
        var displayValue = (obj.style.display!='none')?'none':'block';

    }
    obj.style.display = displayValue;
    setCookie(id, displayValue, 30);
    return;
}

window.onload = function()
{
    toggleList('sidebar_block_content', getCookie('sidebar_block_content'));
    return;
}

function setCookie(name, value, expiredays)
{
    if (expiredays==null) { expiredays=0; }

    var expireDate = new Date();
    expireDate.setDate(expireDate.getDate()+expiredays);

    var cookieVal  = name + '=' +escape(value) + ';expires=' + expireDate.toGMTString();
    document.cookie = cookieVal; 
    return;
}

function getCookie(searchName)
{
  if (document.cookie.length>0)
  {
    var nameValuePair, cookieName, cookieValue
    var pairs = document.cookie.split(';');
    for(var i=0; i<pairs.length; i++)
    {
      nameValuePair = pairs[i].split('='); 
      cookieName    = nameValuePair[0].replace(/^\s+|\s+$/g,'');
      cookieValue   = nameValuePair[1].replace(/^\s+|\s+$/g,'');
      if(cookieName == searchName) { return cookieValue; }
    }
  }
  return false;
}
//]]>

此代码适用于cookie,我想添加淡入淡出效果(如jquery效果)以使用切换。任何人都可以帮我吗? :)谢谢!

3 个答案:

答案 0 :(得分:1)

vanilla-js

有一个淡化元素的片段

转载如下:

var s = document.getElementById('thing').style;
s.opacity = 1;
(function fade(){(s.opacity-=.1)<0?s.display="none":setTimeout(fade,40)})();

与jQuery版本相比:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$('#thing').fadeOut();
</script>

添加小提琴:

&#13;
&#13;
function fadeElement(elem) {
  var s = elem.style;
  s.opacity = 1;
  (function fade(){
    (s.opacity-=.1)<0?s.display="none":setTimeout(fade,40)
  })();
}

fadeElement(document.getElementById('thing'))
&#13;
<div id="thing" style="height: 200px; width: 200px; background: red"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

function toggleList(id, displayValue) {
    $( "#" + id).fadeIn( "slow", function() {
       var obj = document.getElementById(id);
           if(!displayValue)
           {
               var displayValue = (obj.style.display!='none')?'none':'block';

           }
           obj.style.display = displayValue;
           setCookie(id, displayValue, 30);
           return;
    });
}

答案 2 :(得分:0)

因此。 我有这个主题的第一个代码。 我有这条线:

<a href="#" class="toggle_sidebarBody toggle_sdautoHide clickable" title="{L_SD_TOGGLE_SIDEBAR}" onclick="toggleList('sidebar_block_content'); return false;">{L_SD_COLLAPSE_ENTITY}</a>

用于切换,我的内容为X.

当我点击切换按钮时,我希望我的内容隐藏/显示淡入淡出效果。