隐藏文本区域占用空间



所以我有以下代码设置,以便当且仅当用户选中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>

visibilityopacity只是使元素透明,但不让它们消失。为此,您需要将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()等函数,使操作更简单。

你可以使用属性hiddendiv与类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时,元素只是"不可见",但仍然需要空间来放置它,你可能想使用fadeOutfadeIn, slideUpslideDown的jQuery,这将真正隐藏元素,也摆脱了他们的动画空间。您还可以将display属性更改为noneblock,以简单的方式隐藏它

$('#other').on('click', function() {
 if ($(this).is(':checked')) {
  $('.otherCon').slideDown();
 } else {
   $('.otherCon').slideUp();
 }
});

你也可以使用<label for="checkbox id"/>来切换checked状态的复选框点击标签文本

试试https://jsfiddle.net/8qqLmyad/1/

最新更新