获取和设置CS()不起作用..切换高度



我尝试将高度从50px切换到200px。我写这段代码是为了检查高度是否为50px,如果它被设置为200,它的任何其他值都将它设置为50。基本上是一个切换函数

$('.this-row').click(function(){
console.log("click "+$('.this-row').css('height'));
if($('.this-row').css('height','50')){
    $('.this-row').css('height','200')
    }
else 
    $('.this-row').css('height','50')
 });

在css中,我最初有.此行{height:50px}。现在它会检查高度并设置为200,但相反的逻辑在下一次单击

时不起作用

在您的条件下,您正在使用setter,所以在测试它之前,您总是将高度设置为50px。试试这个:

if ($('.this-row').css('height') == '50') {
    $('.this-row').css('height','200')
}
else 
    $('.this-row').css('height','50') 
});

您可以通过使用三元来缩短此时间

$row = $('.this-row');
$row.css('height', $row.css('height') == '50' ? '200' : '50');

或者更好的是,通过使用一个类将UI与标记完全分离:

$('.this-row').toggleClass('tall');
.tall {
    height: 200px;
}

jQuerys toggleClass方法非常适合此操作。

CSS:

.this-row { height: 50px; }
.height2 { height: 200px; }

jQuery:

$('.this-row').click(function(){
    $(this).toggleClass('height2');
});

您想要评估条件中的高度,而不是设置它,将代码更改为如下内容:

$('.this-row').click(function(){
  var height = $('.this-row').css('height');
  console.log("click "+height);
  if(height == '50') {
    $('.this-row').css('height','200')
  }
  else {
    $('.this-row').css('height','50')
  }
});

将测试与类.this-row定义的元素相关联的样式的高度值;由于您要多次处理高度值,因此可以将其读取到局部变量中,以减少重复处理。这个条件是测试高度是否为50px。

最新更新