jquery div扩展背景颜色不透明度变化

时间:2015-01-02 19:11:52

标签: javascript jquery html css css3

使用jQuery lib:

<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.4.js'></script>

我有这个jquery代码:

<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$('#header-out').css('background-color','rgba(255,255,255,.25)').hover(function() {
    $(this).stop().css('background-color','rgba(255,255,255,.80)').animate({
        height: '400px'
    }, 800);

}, function() {
    $(this).stop().css('background-color','rgba(255,255,255,.25)').animate({
        height: '75px'
    }, 800);

});
});//]]>  
</script>

我遇到的问题是背景不透明度不会随着扩展而延迟。

我的目标是让不透明度从.25变为.80,因为div会扩展,而不是立即从.25跳到.80。我希望.80不透明度在div崩溃时返回到.25,而不是在鼠标移除时立即返回.25

我不确定此代码是否是用于我打算做的最佳代码。

总体目标是在鼠标悬停/悬停时扩展标题以及背景不透明度变化。


我尝试过的其他方法:

起初我开始使用CSS给#header-out一个背景:

#header-out {
   background: rgba(255,255, 255, .25);
}

我使用的jquery代码如下:

<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$('#header-out').hover(function() {
    $(this).stop().animate({
        opacity: '.80',
        height: '400px'
    }, 800);

}, function() {
    $(this).stop().animate({
        opacity: '.25',
        height: '75px'
    }, 800);

});
});//]]>  
</script>

我在上述方法中发现的问题是该页面将加载#header-out,不透明度为.25。悬停后,#header-out似乎崩溃到不透明度(.80 - .25)或仅.25而不是返回.80。这就是为什么我决定从我的#header-out中删除CSS而不是尝试在jquery代码中使用它。


最后说明:

html结构如下:

<div id="header-out">
   <div id="header-in">
     Content 
   </div>
</div>

CSS是:

#header-out {
   width:100%;
   height:75px;
   position:fixed;
   top:0;
   left:0;
   z-index:999;
   cursor: pointer; 
}
#header-in {
   width:90%;
   margin:0 auto;
   padding:0;
}
  • 我想在#header-in
  • 中找到我的徽标和菜单
  • 我希望在标题DIV扩展后可以看到更多内容。

2 个答案:

答案 0 :(得分:1)

您可以使用现代浏览器中的过渡在CSS本身中执行此操作。您可以查看所有浏览器都支持转换的that here

#header-out {
    width:100%;
    height:75px;
    position:fixed;
    top:0;
    left:0;
    z-index:999;
    cursor: pointer;
    background: rgba(125,135,105,.25);
    transition: all 0.6s linear;
}
#header-out:hover {
    transition: all 0.6s linear;
    background: rgba(45,65,135,.80);
    height: 400px;  
    color: #fff;
}

See fiddle

答案 1 :(得分:0)

$(document).ready(function(){
$('#header-out').hover(function() {
    $(this).stop().animate({
        'opacity':'.80',
        'height': '400px'
    }, 800);

}, function() {
    $(this).stop().animate({
        'opacity':'.25',
        'height': '70px'
    }, 800);

});
});

请参阅DEMO

相关问题