所以我有以下代码设置,以便当且仅当用户选中Other时,则显示"If Other "框。当盒子被隐藏时,这样做会留下空白空间。当复选框未选中时,是否有办法消除这一点,并向下滚动内容,并在选中其他框时添加"If other box"。
下面是工作代码
$('#other').on('click', function() {
if ($(this).is(':checked')) {
$('.otherCon').css('visibility', 'visible');
} else {
$('.otherCon').css('visibility', 'hidden');
}
});
.otherCon {
visibility: hidden;
}
label {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="userCheck">
<input type="checkbox" id="other" name="Other" value="Other" />
<label>Other</label>
</div>
<div class="otherCon">
<label>If other</label>
<textarea id="text" name="Other Response"></textarea>
</div>
<div>
<label>More info</label>
<textarea id="text" name="More info"></textarea>
</div>
visibility
和opacity
只是使元素透明,但不让它们消失。为此,您需要将display
设置为none
。或者更好,因为你正在使用jQuery, .show()
和.hide()
。
$('#other').on('click', function() {
if ($(this).is(':checked')) {
$('.otherCon').show();
} else {
$('.otherCon').hide();
}
});
或者,因为使用了条件,所以使用.toggle()
:
$('#other').on('click', function() {
$('.otherCon').toggle($(this).is(':checked'));
});
工作的例子:
$('#other').on('click', function() {
$('.otherCon').toggle($(this).is(':checked'));
});
.otherCon {
display: none;
}
label {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="userCheck">
<input type="checkbox" id="other" name="Other" value="Other" />
<label>Other</label>
</div>
<div class="otherCon">
<label>If other</label>
<textarea id="text" name="Other Response"></textarea>
</div>
<div>
<label>More info</label>
<textarea id="text" name="More info"></textarea>
</div>
用display: none
代替。它隐藏了元素,没有任何空间。jQuery提供了hide()、show()和toggle()等函数,使操作更简单。
你可以使用属性hidden
为div
与类otherCon
和改变jquery使用show()
或hide()
或删除if
和添加$('.otherCon').toggle();
$('#other').on('click', function() {
//$('.otherCon').toggle();
if ($(this).is(':checked')) {
$('.otherCon').show();
} else {
$('.otherCon').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="userCheck">
<input type="checkbox" id="other" name="Other" value="Other" />
<label>Other</label>
</div>
<div class="otherCon" hidden>
<label>If other</label>
<textarea id="text" name="Other Response"></textarea>
</div>
<div>
<label>More info</label>
<textarea id="text" name="More info"></textarea>
</div>
当设置visibility
时,元素只是"不可见",但仍然需要空间来放置它,你可能想使用fadeOut
和fadeIn
, slideUp
和slideDown
的jQuery,这将真正隐藏元素,也摆脱了他们的动画空间。您还可以将display
属性更改为none
或block
,以简单的方式隐藏它
$('#other').on('click', function() {
if ($(this).is(':checked')) {
$('.otherCon').slideDown();
} else {
$('.otherCon').slideUp();
}
});
你也可以使用<label for="checkbox id"/>
来切换checked
状态的复选框点击标签文本
试试https://jsfiddle.net/8qqLmyad/1/