CSS3 Transitions: is there an on click option without using JQuery?

烈酒焚心 提交于 2019-12-17 18:52:36

问题


This works great:

<style type="text/css"> 
    div
    {
    width:100px;
    height:100px;
    background:red;
    transition:width 2s;
    -moz-transition:width 2s; /* Firefox 4 */
    -webkit-transition:width 2s; /* Safari and Chrome */
    -o-transition:width 2s; /* Opera */
    }

    div:hover
    {
    width:300px;
    }
    </style>

But does anyone know of a way to do this using click instead of hover? And not involving JQuery?

Thanks!


回答1:


You can write like this:

CSS

input{display:none}
.ani
    {
    width:100px;
    height:100px;
    background:red;
    transition:width 2s;
    -moz-transition:width 2s; /* Firefox 4 */
    -webkit-transition:width 2s; /* Safari and Chrome */
    -o-transition:width 2s; /* Opera */
    display:block;
    }
input:checked + .ani{width:300px;}

HTML

<input type="checkbox" id="button">
<label class="ani" for="button"></label>

Check this http://jsfiddle.net/nMNJE/




回答2:


You have two options, one using javascript and one using the CSS pseudo-class "active". The javascript method will be supported on older browsers, and is what i would recommend. However, to use the CSS method just change div:hover to div:active.

Javascript:

<script type="text/javascript">
function expand(){
    document.getElementById('id').style.width="300px";
}
</script>

CSS:

<style type="text/css"> 
div#id
{
width:100px;
height:100px;
background:red;
transition:width 2s;
-moz-transition:width 2s; /* Firefox 4 */
-webkit-transition:width 2s; /* Safari and Chrome */
-o-transition:width 2s; /* Opera */
}
</style>

HTML:

<div id="id" onClick="expand()">
    Div Content...
</div>



回答3:


Actually there is a click selector without using javasccript. You can affect differente DOM elements using :target pseudo class. If an element is the destination of an anchor target it will get the :target pseudo element (to influence the clicked element just set the ID the same as its anchor tag).

<style>
a { color:black; }
a:target { color:red; }
</style>

<a id="elem" href="#elem">Click me</a>

Here is a fiddle to play with : https://jsfiddle.net/k86b81jv/




回答4:


there is no css selector for clicks without using sass, so using jquery is probably your best bet

$(document).ready(function(){
$('#DIV_ID').click(function(){
$(this).animate({width:'300px'},200);
});
});

((don't forget to include the plugin link in your header!!))

<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>


来源:https://stackoverflow.com/questions/11166580/css3-transitions-is-there-an-on-click-option-without-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!