是的,有限制
我一直在思考一个类似于 cimmanon 的解决方案,只是我知道它需要比这更精致(这就是为什么需要一些时间来回答的原因)。
让我先声明一下,这可能需要一个实际限制(我不知道在您的情况下可能存在的字符数是否有限制)。正如您在我的示例 fiddle 中看到的那样,任何 300+ 都无法解析为更大的尺寸。如果存在上限或未知上限,那么 javascript 确实是您的最佳解决方案。我的示例适用于少于 300 个,并且可能使用不多的代码就可以制作多达 999 个。但是我认为1000+是不合理的。
CSS
/* set default as small size */
[class ^= "txtField"] {
width: 50px;
}
/* weed out 50-99, making sure not to get 5-9 */
[class *= "d5"]:not([class $= "d5"]),
[class *= "d6"]:not([class $= "d6"]),
[class *= "d7"]:not([class $= "d7"]),
[class *= "d8"]:not([class $= "d8"]),
[class *= "d9"]:not([class $= "d9"])
{
width: 80px;
}
/* weed out 100-199, making sure not to get 1 or 10-19
NOTE: this becomes a highly specific selector
*/
[class *= "d1"]:not([class $= "d1"]):not([class $= "d10"]):not([class $= "d11"]):not([class $= "d12"]):not([class $= "d13"]):not([class $= "d14"]):not([class $= "d15"]):not([class $= "d16"]):not([class $= "d17"]):not([class $= "d18"]):not([class $= "d19"])
{
width: 120px;
}
/* weed out 150-199, making sure not to get 15-19
NOTE: because the previous selector is so specific, this one
needed the !important flag (which I hate to use, but here
seemed to be the best and only solution)
*/
[class *= "d15"]:not([class $= "d15"]),
[class *= "d16"]:not([class $= "d16"]),
[class *= "d17"]:not([class $= "d17"]),
[class *= "d18"]:not([class $= "d18"]),
[class *= "d19"]:not([class $= "d19"])
{
width: 150px !important;
}
/* weed out 200-299, making sure not to get 2 or 20-29
NOTE: again high specificity
*/
[class *= "d2"]:not([class $= "d2"]):not([class $= "d20"]):not([class $= "d21"]):not([class $= "d22"]):not([class $= "d23"]):not([class $= "d24"]):not([class $= "d25"]):not([class $= "d26"]):not([class $= "d27"]):not([class $= "d28"]):not([class $= "d29"])
{
width: 180px;
}
/* weed out 250-299, making sure not to get 25-29
NOTE: !important needed again;
also, anything 300+ reverts back to smallest size unless
one keeps going... maybe 999 could be reached "reasonably"
*/
[class *= "d25"]:not([class $= "d25"]),
[class *= "d26"]:not([class $= "d26"]),
[class *= "d27"]:not([class $= "d27"]),
[class *= "d28"]:not([class $= "d28"]),
[class *= "d29"]:not([class $= "d29"])
{
width: 210px !important;
}