2013-08-18 176 views
2

我試圖用按鈕切換div的寬度。單擊按鈕更改元素CSS樣式

期望的效果是單擊「大」使div寬度達到100%,按鈕讀取「Small」將div降低到50%。

Live example - JS Fiddle

HTML

<div class="block"> 
    block 50% 
</div> 
<button>Big</button> 

CSS

.block { 
    background: green; 
    width: 50%; 
    height: 300px; 
    float: left; 
    display: block; 
    color: white; 
} 
button { 
    clear: both; 
    float: left; 
    margin-top: 30px; 
} 
+0

您遇到什麼麻煩? –

+1

我沒有看到任何jQuery代碼,所以我建議你看看這個http://learn.jquery.com/using-jquery-core/css-styling-dimensions/ –

+0

我試圖切換綠色div的樣式通過點擊'Big'按鈕 – Rob

回答

4

試試這個

$(document).ready(
$('#resize').click(function(){ 
    var value = $(this).html(); 
    if(value=='Big'){ 
     $(this).html('Small'); 
     $('div').css('width',"100%"); 
    }else{ 
    $(this).html('Big'); 
    $('div').css('width',"50%"); 
    } 

}) 
) 

http://jsfiddle.net/tvXyL/6/

+0

你正在向'$(document).ready'傳遞一個不正確的參數。你應該把你現在通過的函數換成一個函數。 –

0

你需要使用JavaScript這項工作。從我看到你使用jQuery(如您標記的話),所以這可能會爲你工作:

// Give the button a default state 
$('button').attr('data-state', 'expand'); 

$('button').click(function() { 
    // When clicked 

    if ($(this).attr('data-state') === 'expand') { 

     // If it's in "expand" status, expand the div 
     $('.block').css('width', '100%'); 
     $(this).text('Small').attr('data-state', 'compress'); 
    } else if ($(this).attr('data-state') === 'compress') { 

     // If it's in "compress" state, compress the div 
     $('.block').css('width', '50%'); 
     $(this).text('Big').attr('data-state', 'expand'); 
    } 
}); 

JSFiddle.

0

添加這個jQuery簡單地切換類。

jQuery的

$('button').on('click', function(event) { 
    if($('.block').hasClass('expand') == false) { 
     $('.block').addClass('expand'); 
     $(this).text('Small'); 
    } else { 
     $('.block').removeClass('expand'); 
     $(this).text('Big'); 
    } 
}); 

添加.expand類你的CSS。

CSS

.block.expand { 
    width: 100%; 
} 

的jsfiddle這裏:http://jsfiddle.net/RyN7d/1/