2015-11-06 31 views
0

我想讓用戶鼠標進入.container時,#facial會向左滑動,暫停一秒,然後增加它的寬度以填充它的容器的寬度。如何使用JQuery增加Div內的寬度--Newby

現在#facial正確滑動,但是當我嘗試讓#facial填充整個寬度時,它會彈出它的容器。此外,我希望它暫停一會,以顯示從進入中間到增加寬度時的轉換速度。

這是我的代碼。

$(document).ready(function() { 
    $('.container').mouseenter(function(){ 
     // When mouse enters the .container, #facial slides to center of .container. 
     $('#facial').animate({right: '122px'}); 
     // #facial expands it's width to fit .container. 
     $('#facial').width(400); 
    }); 

}); 

Here is my Demo

回答

0

改爲使用百分比和使用絕對定位。

https://jsfiddle.net/sy4pv8z3/

的Javascript:

$(document).ready(function() { 
    $('.container').mouseenter(function(){ 
     // When mouse enters the .container, #facial slides to center of .container. 
     $('#facial').animate({right: '25%'}) 
        .delay(500) 
        .animate({right: 0, width: '100%'}); 
    }); 
}); 

CSS:

body { 
    background-color:#d6d6d6; 
} 
.container { 
    position: relative; 
    margin: 200px auto; 
    background-color:red; 
    width:478px; 
    height:200px; 
} 
img { 
    float:left; 
    width:239px; 
    height:200px;  
} 
#facial { 
    position:absolute; 
    right: 0; 
    width:239px; 
    height:200px; 
    background-color:#008aaf; 
} 
#facial h1, #facial h2 { 
    text-align:center; 
    margin-top:30px; 
    color:#FFFFFF; 
} 
+0

謝謝一堆!我最終在我的代碼中使用了這個。 – StinkyTofu

0

$('#facial').animate({right: '122px'}).delay(1000).animate({width: '400px'});

1

\t $(document).ready(function() { 
 
\t $('.container').mouseenter(function() { 
 
\t  // When mouse enters the .container, #facial slides to center of .container. 
 
\t  $('#facial').animate({ 
 
\t  right: '122px', 
 
\t  position: 'absolute' 
 
\t  }).delay(500).animate({ 
 
\t  right: '0px', 
 
\t  width: '478px' 
 
\t  }); 
 
\t  // #facial expands it's width to fit .container. 
 
\t  $('#facial').width(250); // .width(400) causes it to pop-out 
 
\t }); 
 

 
\t });
body { 
 
    background-color: #d6d6d6; 
 
} 
 
.container { 
 
    margin: 200px auto; 
 
    background-color: red; 
 
    width: 478px; 
 
    height: 200px; 
 
} 
 
img { 
 
    float: left; 
 
    width: 239px; 
 
    height: 200px; 
 
} 
 
.image { 
 
    position: absolute; 
 
} 
 
#facial { 
 
    position: relative; 
 
    float: right; 
 
    width: 239px; 
 
    height: 200px; 
 
    background-color: #008aaf; 
 
} 
 
#facial h1, 
 
#facial h2 { 
 
    text-align: center; 
 
    margin-top: 30px; 
 
    color: #FFFFFF; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 

 
    <div class="image"> 
 
    <img src="http://s23.postimg.org/enn2yyh7v/Facial.jpg" alt="Facial - Marketing Material" /> 
 
    </div> 
 

 
    <div id="facial"> 
 
    <h1>Facial</h1> 
 
    <h2>Marketing Material</h2> 
 
    </div> 
 

 
</div>

+0

投票答:仔細檢查了jQuery側 – Aizen

+0

老天的 「絕對」!謝謝@Aizen :)。沒有注意到錯字 –