2014-08-28 220 views
20

我在我的網站上有一個包含所有內容的部分,但是我想要一個帶有隱藏內容的「側邊欄」在按下外部按鈕時從左側順利出現。在沒有jQuery的情況下切換HTML元素的類

CSS過渡可以處理平滑沒有問題,並且jQuery toggle()可以在類之間切換以將隱藏的div移入和移出屏幕。

如何在不使用jQuery的情況下獲得相同的效果?

+1

http://vanilla-js.com/ – joews 2014-08-28 08:15:53

+1

@joews他說沒有的jQuery,反正,[這](http://css-tricks.com/controlling-css-animations-transitions -javascript /)可能對你有幫助 – Yaje 2014-08-28 08:17:28

+6

20+那些沒有jQuery無法工作的JavaScript專家遠離javascript專家 – 2014-08-28 08:21:07

回答

29

您可以通過CSS3只實現它:

<label for="showblock">Show Block</label> 
<input type="checkbox" id="showblock" /> 

<div id="block"> 
    Hello World 
</div> 

而CSS部分:

#block { 
    background: yellow; 
    height: 0; 
    overflow: hidden; 
    transition: height 300ms linear; 
} 

label { 
    cursor: pointer; 
} 

#showblock { 
    display: none; 
} 

#showblock:checked + #block { 
    height: 40px; 
} 

魔術是隱藏checkbox和CSS的:checked選擇。

Working jsFiddle Demo

+3

這是完美的!甚至沒有任何js!如果可以的話,我會多次讚揚這個答案:D我喜歡這個解決方案!它比我能想象到的最簡單的js更好!你先生,贏得5000個互聯網,但因爲我沒有15 +代表無法贊成,我只是給你這個,希望它可以讓你的臉上帶着微笑; https://www.youtube.com/watch?v=V-1gjOKKoRY – KittenCodings 2014-08-28 08:44:00

+2

一個字:輝煌! – 2014-08-28 08:51:39

+0

純HTML + CSS,太棒了! +1 – fbiazi 2015-08-31 11:54:43

18

如果你感到快樂,只支持更現代的瀏覽器,您可以切換使用classList.toggle()函數的類:

var element = document.getElementById('sidebar'); 
var trigger = document.getElementById('js-toggle-sidebar'); // or whatever triggers the toggle 

trigger.addEventListener('click', function(e) { 
    e.preventDefault(); 
    element.classList.toggle('sidebar-active'); // or whatever your active class is 
}); 

這應該做你需要的一切 - 如果你有一個以上的觸發我建議使用document.querySelectorAll(selector)

希望幫助

+2

他很高興只支持現代瀏覽器,因爲正如他提到的那樣,他正在使用css3轉換。 – blex 2014-08-28 08:20:45

+0

夠公平,切換! :) – 2014-08-28 08:25:42

+0

所以有一個簡單的方法來切換沒有jQuery的類!這太棒了,謝謝! :D – KittenCodings 2014-08-28 08:31:18

5

你可以使用JavaScript(jQuery的沒有)和類ID得到任何元素的屬性: element.className 所以有這樣的一個函數:

更新: 因爲這正成爲一種有點流行我更新了功能,使其更好。

function toggleClass(element, toggleClass){ 
    var currentClass = element.className; 
    var newClass; 
    if(currentClass.split(" ").indexOf(toggleClass) > -1){ //has class 
     newClass = currentClass.replace(new RegExp('\\b'+toggleClass+'\\b','g'),"") 
    }else{ 
     newClass = currentClass + " " + toggleClass; 
    } 
    element.className = newClass.trim(); 
} 
+0

啊......很好,我可以做得比我原先打算使用的還要多,非常感謝:) – KittenCodings 2014-08-28 08:33:52

+0

你知道「newClass」變量不會是本地的嗎? – 2017-05-14 14:28:12

+0

很好的答案!請將函數內的第一行更改爲'var currentClass = element.className || ''處理空類屬性:) – ymz 2017-07-03 13:39:25

0
function init() { 

    animateCSS(document.getElementById("slide"), 250, { 
     left: function (timePercent, frame) { 

      var endPoint = 128, 
       startPoint = 0, 
       pathLength = endPoint - startPoint, 
       base = 64,       //slope of the curve 
       currentPos = Math.floor(startPoint + (Math.pow(base, timePercent) - 1)/(base - 1) * pathLength); 

      return currentPos + "px"; 
     } 
    }, function (element) { 
     element.style.left = "128px"; 
    }); 

}; 
var JobType = function() { 
    if (!(this instanceof JobType)) { 
     return new JobType(arguments[0]); 
    }; 
    var arg = arguments[0]; 
    this.fn = arg["fn"]; 
    this.delay = arg["delay"]; 
    this.startTime = arg["startTime"]; 
    this.comment = arg["comment"]; 
    this.elapsed = 0; 
}; 
function JobManager() { 
    if (!(this instanceof JobManager)) { 
     return new JobManager(); 
    }; 
    var instance; 
    JobManager = function() { 
     return instance; 
    }; 
    JobManager.prototype = this; 
    instance = new JobManager(); 
    instance.constructor = JobManager; 
    var jobQueue = []; 
    var startedFlag = false; 
    var inProcess = false; 
    var currentJob = null; 
    var timerID = -1; 
    var start = function() { 
     if (jobQueue.length) { 
      startedFlag = true; 
      currentJob = jobQueue.shift(); 
      var startOver = currentJob.delay - ((new Date()).getTime() - currentJob.startTime); 
      timerID = setTimeout(function() { 
       inProcess = true; 
       currentJob.fn(); 
       if (jobQueue.length) { 
        try { 
         while ((jobQueue[0].delay - ((new Date()).getTime() - currentJob.startTime)) <= 0) { 
          currentJob = jobQueue.shift(); 
          currentJob.fn(); 
         }; 
        } 
        catch (e) { }; 
       } 
       inProcess = false; 
       start(); 
      }, (startOver > 0 ? startOver : 0)); 
     } 
     else { 
      startedFlag = false; 
      timerID = -1; 
     }; 
    }; 
    instance.add = function (newJob) { 
     if (newJob instanceof JobType) { 
      stopCurrent(); 
      var jobQueueLength = jobQueue.length; 
      if (!jobQueueLength) { 

       jobQueue.push(newJob); 
      } 
      else { 
       var currentTime = (new Date()).getTime(), 
        insertedFlag = false; 
       for (var i = 0; i < jobQueueLength; i++) { 
        var tempJob = jobQueue[i], 
         tempJobElapsed = currentTime - tempJob["startTime"], 
         tempJobDelay = tempJob["delay"] - tempJobElapsed; 
        tempJob["elapsed"] = tempJobElapsed; 
        if (newJob["delay"] <= tempJobDelay) { 
         if (!insertedFlag) { 
          jobQueue.splice(i, 0, newJob); 
          insertedFlag = true; 
         } 
        }; 
        if (i === (jobQueueLength - 1)) { 
         if (!insertedFlag) { 
          jobQueue.push(newJob); 
          insertedFlag = true; 
         } 
        } 
       }; 
      }; 
      if ((!startedFlag) && (!inProcess)) { 
       start(); 
      }; 
      return true; 
     } 
     else { 
      return false; 
     }; 
    }; 
    var stopCurrent = function() { 
     if (timerID >= 0) { 
      if (!inProcess) { 
       clearTimeout(timerID); 
       timerID = -1; 
       if (currentJob) { 
        jobQueue.unshift(currentJob); 
       }; 
      }; 
      startedFlag = false; 
     }; 
    }; 
    return instance; 
}; 
function animateCSS(element, duration, animation, whendone) { 
    var frame = 0, 
     elapsedTime = 0, 
     timePercent = 0, 
     startTime = new Date().getTime(), 
     endTime = startTime + duration, 
     fps = 0, 
     averageRenderTime = 1000, 
     normalRenderTime = 1000/25, 
     myJobManager = JobManager(); 
    var inQueue = myJobManager.add(JobType({ 
     "fn": displayNextFrame, 
     "delay": 0, 
     "startTime": (new Date).getTime(), 
     "comment": "start new animation" 
    })); 
    function playFrame() { 
     for (var cssprop in animation) { 
      try { 
       element.style[cssprop] = animation[cssprop].call(element, timePercent, frame); 
      } catch (e) { } 
     }; 
    }; 
    function displayNextFrame() { 
     elapsedTime = (new Date().getTime()) - startTime; 
     timePercent = elapsedTime/duration; 
     if (elapsedTime >= duration) { 
      playFrame(); 
      if (whendone) { 
       whendone(element); 
      }; 
      return; 
     }; 

     playFrame(); 
     frame++; 
     averageRenderTime = elapsedTime/frame; 
     fps = 1000/averageRenderTime; 
     inQueue = myJobManager.add(JobType({ 
      "fn": displayNextFrame, 
      "delay": (fps < 15 ? 0 : normalRenderTime - averageRenderTime), 
      "startTime": (new Date).getTime(), 
      "comment": frame 
     })); 
    } 
}; 
(function() { 
    if (this.addEventListener) { 
     this.addEventListener("load", init, false) 
    } 
    else { 
     window.onload = init; 
    } 
}()); 
+0

http://jsfiddle.net/Greck_geek/aw2rtu30/ – Greck 2014-08-28 08:32:05

+0

哇,只是..哇,謝謝! :D – KittenCodings 2014-08-28 08:36:25

0
// By Plain Javascript 
// this code will work on most of browsers. 
function hasClass(ele, clsName) { 
    var el = ele.className; 
    el = el.split(' '); 
    if(el.indexOf(clsName) > -1){ 
     var cIndex = el.indexOf(clsName); 
     el.splice(cIndex, 1); 
     ele.className = " "; 
     el.forEach(function(item, index){ 
      ele.className += " " + item; 
     }) 
    } 
    else { 
     el.push(clsName); 
     ele.className = " "; 
     el.forEach(function(item, index){ 
      ele.className += " " + item; 
     }) 
    } 
} 

var btn = document.getElementById('btn'); 
var ele = document.getElementById('temp'); 

btn.addEventListener('click', function(){ 
    hasClass(ele, 'active') 
}) 
+0

關於codepen的示例視圖http://codepen.io/kaushik/pen/ObXZqV – 2016-11-16 06:10:36

相關問題