我很想知道是否有人可以告诉我为什么这不起作用?它只适用于一次。我正在尝试用基础的切换对象切换div
的高度。当我点击#new标签时它也完美切换。但那不是想法。
var open = 0;
$('#newtopicbutton').click(function() {
if (open === 0) {
$('#new').css({
'height': '440px',
'color': 'white',
'font-size': '44px'
});
open = 1;
} else {
if (open === 1) {
$('#new').css({
'height': '48px',
'color': 'white',
'font-size': '44px'
});
open = 0;
}
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="new" class="large-3 medium-3 small-3 columns" style="padding-top:10px;background:#2f2f2f;margin-top:20px;height:440px;color:white;font-weight:700;font-size:14px !important;">
<div id="newtopicbutton" class="switch small">
<input class="switch-input" style="background:red;" id="exampleSwitch" checked="true" type="checkbox" name="exampleSwitch">
<label class="switch-paddle" for="exampleSwitch">
<span class="show-for-sr float-right">NEW TOPICS</span>
</label>
</div>
</div>
&#13;
只适用一次。
答案 0 :(得分:2)
你只需要在输入按钮上听取click事件而不是在div
周围
var open = 0;
$('#exampleSwitch').click(function() {
if (open===0) {
$('#new').css({
'height': '440px',
'color': 'white',
'font-size': '44px'
});
open=1;}
else{
if (open===1) {
$('#new').css({
'height': '48px',
'color': 'white',
'font-size': '44px'
});
open=0;}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="new" class="large-3 medium-3 small-3 columns" style="padding-top:10px;background:#2f2f2f;margin-top:20px;height:440px;color:white;font-weight:700;font-size:14px !important;">
<div id="newtopicbutton" class="switch small">
<input class="switch-input" style="background:red;" id="exampleSwitch" checked="true" type="checkbox" name="exampleSwitch">
<label class="switch-paddle" for="exampleSwitch">
<span class="show-for-sr float-right">NEW TOPICS</span>
</label>
</div>
</div>
但正如评论中所提到的,最好使用.toggleClass
答案 1 :(得分:-1)
我修改了你的代码:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<body>
<div id="new" class="large-3 medium-3 small-3 columns" style="padding-top:10px;background:#2f2f2f;margin-top:20px;height:440px;color:white;font-weight:700;font-size:14px !important;">
<div id="newtopicbutton" class="switch small">
<input class="switch-input" style="background:red;" id="exampleSwitch" checked="true" type="checkbox" name="exampleSwitch">
<label class="switch-paddle" for="exampleSwitch">
<span class="show-for-sr float-right">NEW TOPICS</span>
</label>
</div>
</div>
<style>
#newtopicbutton {
font-size: 14px;
}
</style>
<script>
var open = 1;
$('#newtopicbutton, .switch-paddle span').click(function() {
if (open===0) {
$('#new').css({
'height': '440px',
'color': 'white',
'font-size': '44px'
});
open=1;
}
else {
if (open===1) {
$('#new').css({
'height': '48px',
'color': 'white',
'font-size': '44px'
});
open=0;
}
}
console.log(open);
});
</script>
</body>
</html>