Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - Toggle class on HTML element without jQuery

I have a section on my website which holds all the content, but I want a "sidebar" with hidden content to smoothly appear from the left at the push of an external button.

CSS transitions can handle the smoothness no problem, and jQuery toggle() can switch between classes to move the hidden div in and out of the screen.

How can I get the same effect without using jQuery?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can implement it only by CSS3:

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

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

And the CSS part:

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

label {
    cursor: pointer;
}

#showblock {
    display: none;
}

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

The magic is the hidden checkbox and the :checked selector in CSS.

Working jsFiddle Demo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...