javascript - 为什么第 nth-of-type 检测仅在 Firefox 中失败?

标签 javascript jquery css

我正在使用 JavaScript/jQuery 检测浏览器是否支持 nth-of-type CSS3 伪类。在 CSS 中分配了一个 5px padding-left(见下面的代码),如果 JS/jQ 可以通过 $(document).ready() 读取它,则检测成功.

Chrome 26、IE9、Win Safari 5.1 和 Opera 12 一切正常,所有这些都检测到 5px 设置。但是,确实支持 nth-of-type 的 Firefox 20 将 padding-left 设置显示为 0px,因此错误地未能通过测试。为什么 nth-of-type 检测仅在 Firefox 中失败?

示例代码。 (从我的生产代码中删除。如果您想试验它,也可以在 http://jsfiddle.net/jma7777/ZnzBN/1/ 获得。打开控制台查看 padding-left 检测结果。)

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Pseudo Class Nth-of-Type Detector</title>
<style>
#checkPsdoClass1 tr.rows:nth-of-type(odd) {
  padding-left: 5px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
  // Checks for style assigned to :nth-of-type(odd)
  if ($('#checkPsdoClass2').css('padding-left') !== '5px') {
    $('#pseudoClassDemo').html('<p>Your browser does not support the <code>:nth-of-type</code> pseudo-class.');
  }
  console.log($('#checkPsdoClass2').css('padding-left'));  // Modern browsers log 5px except Firefox which logs 0px
  console.log($('#checkPsdoClass1 tr.rows:nth-of-type(odd)').css('padding-left'));  // Modern browsers log 5px except Firefox which logs 0px
  console.log($('tr.rows:nth-of-type(odd)').css('padding-left'));  // Modern browsers log 5px except Firefox which logs 0px
});
</script>
</head>

<body>
<table id="checkPsdoClass1"><tr id="checkPsdoClass2" class="rows"><td><p id="checkPdsoElmnt">This table is used to test if the browser supports the nth-of-type pseudo-class.</p></td></tr></table>
</body>

</html>

最佳答案

我认为问题是 Firefox 没有对表格行元素应用填充;见MDN详情:

[padding] applies to all elements except table-row-group, table-header-group, table-footer-group, table-row, table-column-group and table-column

尝试将填充分配给第一个子单元格:

#checkPsdoClass1 tr.rows:nth-of-type(odd) td:first-child {
  padding-left: 5px;
}

关于javascript - 为什么第 nth-of-type 检测仅在 Firefox 中失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16471701/

相关文章:

javascript - 隐藏侧边栏 - marginRight/display CSS bug with Javascript

css - 用于鼠标悬停的 ngx-datatable css 样式

javascript - 下拉列表不会与下拉按钮垂直对齐

javascript - 在源代码控制下管理 WebStorm 中的第 3 方 JavaScript 库

jquery - 有没有更有效的方法来编写 $ ('parent > child' )?

javascript - 将样式应用于不在任何 HTML 标记内的文本?

javascript - 单元测试 Mootools 代码的最佳解决方案

html - 帮助将 CSS 样式从标签转换到标签

javascript - jQuery 队列事件

javascript - Angular JS $http 与 SharePoint Rest 解析响应