在没有jQuery的情况下切换HTML元素上的类

时间:2014-08-28 08:14:06

标签: javascript html css

我的网站上有一个部分包含所有内容,但我想要一个"侧边栏"隐藏的内容可以通过按下外部按钮从左侧平滑显示。

CSS过渡可以处理平滑性没问题,jQuery toggle()可以在类之间切换,将隐藏的div移入和移出屏幕。

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

7 个答案:

答案 0 :(得分:31)

您只能通过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;
}

魔法是CSS中隐藏的checkbox:checked选择器。

Working jsFiddle Demo

答案 1 :(得分:23)

如果您乐意只支持更多现代浏览器,可以使用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 :(得分:5)

你可以通过javascript获取任何元素(没有jquery),并且类是一个属性: 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();
}

答案 3 :(得分: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;
    }
}());

答案 4 :(得分: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')
})

答案 5 :(得分:0)

仅HTML

您可以使用<summary>。以下代码没有任何依赖性。 没有JavaScript,根本没有CSS,只有HTML。

<div class="bd-example">
  <details open="">
    <summary>Some details</summary>
    <p>More info about the details.</p>
  </details>

  <details>
    <summary>Even more details</summary>
    <p>Here are even more details about the details.</p>
  </details>
</div>

有关更多详细信息,请转到MDN official docs

答案 6 :(得分:0)

我没有测试,但下面的代码应工作。

<script>

function toggleClass(){
      var element = document.getElementById("a");
      element.classList.toggle("b");
    }
    document.getElementById("c").addEventListener('click', toggleClass )

</script>