Need to know in jQuery if a max-width value is in % or px
jQuery 中有一些方法可以知道 CSS 页面中定义的元素的最大宽度值是 % 还是 px,因为 jQuery 总是返回 px 中的值。
我是说……
1
2 3 |
.contain {
max-width:80%; } |
jQuery -> .contain 在 %!
1
2 3 |
.contain {
max-width:80px; } |
jQuery -> .contain 在 px 中!
谢谢!
1
|
$(‘.contain’).css(‘max-width’)
|
它会返回一个字符串,要么是”80px”要么是”80%”
然后就可以用indexOf来查找是否有”px”或者”%”
1
2 3 4 5 |
if ($(‘.contain’).css(‘max-width’).indexOf(“px”) !== –1) {
//is in px } else if ($(‘.contain’).css(‘max-width’).indexOf(“%”) !== –1) { //is in % } |
- 您知道我们可以访问样式表定义的这些属性的”列表类型”的引用吗…由于此解决方案不适用于 width?这将是有用的……;)
- 即使这在 Chrome 中有效,但在 Firefox 中无效。
奇怪的是,Louys Patrice Bessette 和 Mayday 都是对的。
Mayday 的答案是正确的…如果你在 Chrome 中测试它! .css(‘width’) 将在 px 中返回(即使在 % 中设置),而 .css(‘max-width’) 将在使用该单位时返回 %!然而,在 Firefox 中,该值始终为 px。您可以使用下面的代码对此进行测试,并在 Firefox 和 Chrome 中打开。
1
2 |
console.log($(‘div’).css(‘max-width’));
console.log($(‘div’).css(‘width’)); |
1
2 3 |
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”>
Bananas |
由此我们可以说 Louys Patrice Bessette 指出你不能这样做是正确的。这是真的,如果您在谈论 jQuery\\ 的 CSS 方法 – 可能还有任何类似 getComputedStyle 的方法。
不过,您可以做的是解析样式表并读取样式中写入的实际值。还有许多其他答案可以解决这个问题,所以请查看它们(您可以使用搜索功能查找更多):
- 在 JavaScript / jQuery 中解析 CSS
- JavaScript 的 CSS 解析器?
或者您可以简单地将 CSS 文件作为文本文件读取,然后使用正则表达式查找您需要的值。 (但是,这可能会更慢或至少更容易出错。)
- 如何在 JavaScript 中读取文本文件
- 通过 JavaScript 访问 CSS 文件内容
- 谢谢,我已将此答案添加为书签以供将来参考。 ;)
- 哇!我可以看到我的问题真的很复杂嘿嘿嘿……我认为这是目前的方式……谢谢!
来自 jQuery .css() 页面的引用。
?The .css() method is a convenient way to get a computed style property (…)?
?Note that the computed style of an element may not be the same as the value specified for that element in a style sheet. For example, computed styles of dimensions are almost always pixels, but they can be specified as em, ex, px or % in a style sheet.?
这是一个使用最新 jQuery 版本 (3.0.0) 的测试 Fiddle。
所以…简单的答案是否定的。
- 奇怪的是,不同浏览器的行为不同。在 Chrome 和 FF 中试试这个小提琴,例如:jsfiddle.net/w9ykz72m
- 哇!好吧……那么下一个问题是:是否有这些可访问属性的列表?为了不丢失分数,我删除了我的答案……但问题仍然存在。
- 我决定取消删除…因为 Bram Vanroys anwer 指的是它。对于未来的读者。
来源:https://www.codenong.com/38119538/