2013-01-20 223 views
0

我想做很简单的事情,设置div的高度取决于高度是多少。 所以当网站加载的高度是45px,点击后按钮高度是100px。下一次点击后,我想我的身高回到45px。我使用jQuery,代码如下: http://codepen.io/zlyfenek/pen/pAcaw 感谢您的任何帮助,因为我是jQuery的新手。javascript设置高度

回答

1

您可以使用jQuery的.toggleClass()函数。

$(function(){ 
    $('.yourButton').click(function(){ 
     $('.yourDiv').toggleClass('big'); 
    }); 
}); 

演示:http://jsfiddle.net/FYyU6/

注:

big CSS类应该出现在你小班Order Matters后。

+0

不错,我会试试看! :) – user1995067

0

您应该只是有一个类,设置高度为100px,然后拨动它,当你点击按钮:

.opened { height: 100px; } 

$("button").on("click", function() { 
    $(".con_b").toggleClass("opened"); 
}) 
0
function showHeight(ele, h) { 
$("div").text("The height for the " + ele + 
" is " + h + "px."); 
} 

// use .on instead of .one, .one will online listen for a click one time, 
// so your second click will not be seen 
$("button").on('click', function() { 
    if ($(".con_b").height() == 45) 
    { 
    $(".con_b").height(100); 
    } 
    else 
    { 
    // show height and change height should be two different actions 
    $('.con_b').height(45); 
    showHeight(".con_b",$(".con_b").height()); 
    } 

}); 
1

变化$("button").one$("button").on

0
function showHeight(ele, h) { 
$("div").text("The height for the " + ele + 
" is " + h + "px."); 
} 
$("button").on('click', function() { 

    if ($(".con_b").height() == 45) 
    { 
    $(".con_b").height(100); 
    } 
    else 
    { 
    $(".con_b").height(45); 
    } 

$("button").on不是$("button").one