顺利改变CSS

时间:2012-06-11 11:44:14

标签: javascript jquery css smooth

我的情况如下:

我有以下功能

var showHideMemberContent = function(){
if(isHidden === false){
    $("#showHideMemberContent").text("Member Content");
    $("#main").css("height","-=187");
    $('#mainBottom').hide('slow', function() {
        isHidden = true;
    });
} else {
    $("#showHideMemberContent").text("Verberg");
    $("#main").css("height","+=187");
    $('#mainBottom').show('slow', function() {
        isHidden = false;
    });
}
};

因此,当函数执行时,它会隐藏“mainBottom”div。 “主”div应该减少/增加其高度。 它是这样做的,但我需要知道是否有办法顺利地做到这一点。

谢谢。

5 个答案:

答案 0 :(得分:6)

您可以使用CSS来实现此目的。只需将此规则添加到#main的CSS声明中:

#main {
    -khtml-transition: height 0.3s ease;
    -moz-transition: height 0.3s ease;
    -ms-transition: height 0.3s ease;
    -o-transition: height 0.3s ease;
    -webkit-transition: height 0.3s ease;
    transition: height 0.3s ease;
}

这里height部分定义了应用转换的属性,0.3s定义了从一种状态转换到另一种状态所需的时间,ease属性定义了函数为了过渡。轻松将缓慢加速至50%过渡,然后减速至100%。

使用CSS而不是jQuery的动画功能的优点是CSS转换在支持时是硬件加速的,并且将更加平滑和高效。缺点是一些过时的浏览器版本不支持这种效果,但它只会回归到非动画高度变化,而不是破坏。

要了解有关CSS过渡的更多信息,请按照以下链接访问Mozilla的文章。它们是这类事物的绝佳参考,也是开始学习,甚至了解你的知识的好地方。我还在下面列举了这种技术的一个例子。

MDN article on transitions.

Here is a jsfiddle example.

答案 1 :(得分:5)

是的,请使用jquerys animate()方法,http://api.jquery.com/animate/

如果要使用“线性”或“摇摆”以外的缓动类型,请包含jquery ui。它作为第二个参数(字符串)传递给animate方法。 http://jqueryui.com/demos/effect/easing.html

示例(加载了jquery ui):

$(selector).animate({ height: '200px' }, 'easeInOutCubic', function(){ 
    /* animation comlete */ 
});

另外,处理您的接受率。

答案 2 :(得分:0)

您可以使用animate:

var oldHeight = $("#main").height();
$("#main").animate({'height', oldHeight + 187}, { duration: 500, queue: false });

答案 3 :(得分:0)

如果你想使用css和类而不是style属性,你可以使用jquery-ui的switchClass()toggleClass()方法http://docs.jquery.com/UI/Effects/switchClass http://jqueryui.com/demos / toggleClass /

答案 4 :(得分:0)

使用animate()...

var showHideMemberContent = function(){
if(isHidden === false){
    $("#showHideMemberContent").text("Member Content");
    $("#main").animate({height:-=187}, 300);
    $('#mainBottom').hide('slow', function() {
        isHidden = true;
    });
} else {
    $("#showHideMemberContent").text("Verberg");
    $("#main").animate({height:+=187}, 300);
    $('#mainBottom').show('slow', function() {
        isHidden = false;
    });
}
    };