单击按钮更改元素CSS样式

时间:2013-08-18 20:34:47

标签: jquery css

我正在尝试用按钮切换div的宽度。

想要的效果是单击'Big'使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;
}

3 个答案:

答案 0 :(得分: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/

答案 1 :(得分: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.

答案 2 :(得分: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');
    }
});

在CSS中添加.expand类。

<强> CSS

.block.expand {
    width: 100%;
}

JS在这里:http://jsfiddle.net/RyN7d/1/

相关问题