简体   繁体   English

根据条件设置 CSS 属性

[英]Set CSS attribute based on condition

I have a condition below which sets a CSS grid class based on the usecase length below:我有一个条件,它根据以下用usecase长度设置 CSS 网格 class:

jQuery(".uc"+useCases).addClass((landingPageData.description.useCases.length == 2) ?  'ibm-col-12-6' : 
 (landingPageData.description.useCases.length == 3) ? 'ibm-col-12-4' : 'ibm-col-12-3').attr('style','display:block');

Using the same method I want to add a width of % to a CSS class .ibm-columns based on the same above condition.使用相同的方法,我想基于上述相同的条件将 % 的宽度添加到 CSS class .ibm .ibm-columns

Below syntax is just a representation but I need the proper syntax下面的语法只是一个表示,但我需要正确的语法

jQuery(".ibm-columns").css((landingPageData.description.useCases.length == 2) ? 'width: 60%;' : 
 (landingPageData.description.useCases.length == 3) ? 'width: 70%;' : 'width: 95%;');

The issue is your syntax.问题是你的语法。 css() accepts two arguments, the rule name and its value, yet you supply them both as a single string. css()接受两个 arguments、规则名称及其值,但您将它们都作为单个字符串提供。

To fix this supply the values in an object:要修复此问题,请提供 object 中的值:

jQuery(".ibm-columns").css((landingPageData.description.useCases.length == 2) ? 
   { 'width': '60%' } : 
   (landingPageData.description.useCases.length == 3) ? 
      { 'width': '70%' } : 
      { 'width': '95%' });

I would also suggest you break the ternary out to store the value in its own variable and supply that to css() to make the code more readable:我还建议您打破三元组以将值存储在其自己的变量中并将其提供给css()以使代码更具可读性:

let width = landingPageData.description.useCases.length == 2 ? '60%' :
    landingPageData.description.useCases.length == 3 ? '70%' : '95%';

jQuery(".ibm-columns").css('width', width);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM