CSS改变样式/动画样式使用类或javascript

CSS change style/animate style using class or javascript?

本文关键字:样式 javascript 动画 改变 CSS      更新时间:2023-09-26

我在新网站工作,我有问题。我是否应该使用类或javascript代码来改变样式,例如:

class way:

$('.class').hover(function()
{
    $(this).addClass('nameofclass');
},function()
{
    $(this).removeClass('nameofclass');
}

javascript方式:

$('.class').hover(function()
{
    $(this).css('property','value');
},function()
{
    $(this).css('property','value');
}

关于动画的相同问题,但为了在动画中使用类,我需要使用插件。我应该使用插件来允许类动画吗?

改变类,然后样式在CSS中设置,行为在JS中。

这也有一个好处,你可以在支持CSS转场的浏览器中使用CSS转场,而在旧浏览器中使用animate,通过在需要的地方添加transition属性,然后在新浏览器中使用CSS而不是jQuery中的animate。

例如,假设你想淡出一个div:

CSS

.fade {
    opacity:0;
}
.box {
    width:100px;
    height:100px;
    background-color:red;
    -webkit-transition:all ease-in-out 0.6s;
    -moz-transition:all ease-in-out 0.6s;
    -ms-transition:all ease-in-out 0.6s;
    -o-transition:all ease-in-out 0.6s;
    transition:all ease-in-out 0.6s;
}
HTML

<div class="box"></div>

你的javascript可以像这样:

JS

$(document).ready(function() {
    $(".box").click(function(){
         $(this).toggleClass("fade");
    });
});

在非过渡浏览器中,你不会得到淡出。要添加这些,你可以使用animate将其动画到属性中。

有关过渡的更多信息,请查看http://css3.bradshawenterprises.com/。