如何使用动画切换div的宽度?
HTML:
<div id="toggle-button"></div>
<div id="toggle"></div>?
Run Code Online (Sandbox Code Playgroud)
CSS:
#toggle{
height:200px;
width:200px;
background:red;
}
#toggle-button{
height:20px;
width:20px;
background:blue;
}
Run Code Online (Sandbox Code Playgroud)
jQuery的:
$(document).ready( function(){
$('#toggle-button').click( function() {
$('#toggle').toggle(function() {
$('#toggle').animate({width:"200px"});
}, function() {
$('#toggle').animate({width:"300px"});
});
});
});?
Run Code Online (Sandbox Code Playgroud)
不起作用的示例:http: //jsfiddle.net/ZfHZV/1/
编辑:我的目标是在点击蓝色div时更改宽度
Ror*_*san 18
试试这个:
$(document).ready( function(){
$('#toggle-button').click( function() {
var toggleWidth = $("#toggle").width() == 300 ? "200px" : "300px";
$('#toggle').animate({ width: toggleWidth });
});
});
Run Code Online (Sandbox Code Playgroud)
好家伙!你的代码有效,你只是不明白它的作用......
$('#toggle-button').click( function() { // Execute when the toggle button is clicked.
$('#toggle').toggle(function() { // Attach toggle function that fire different
// callback when clicked.
$('#toggle').animate({width:"200px"});
}, function() {
$('#toggle').animate({width:"300px"});
});
});
Run Code Online (Sandbox Code Playgroud)
点击蓝色div,然后点击红色div几次,看看它是如何工作的.
请注意,您最好附加切换点击回调,one而不是click避免多次回调点击:
$('#toggle-button').one('click', function() {
$('#toggle').toggle(function() {
$('#toggle').animate({width:"200px"});
}, function() {
$('#toggle').animate({width:"300px"});
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39475 次 |
| 最近记录: |