7

在我的 CSS 中,我有一个必须应用于所有文本字段的规则(使用 CSS3 选择器input[type=text].

我也使用jQuery。某些浏览器(例如 Internet Explorer 6)不支持 CSS 选择器的这种形式。所以我的解决方法是在 CSS 中添加一个额外的类名:

input[type=text], .workaround_classname{
  /* css styling goes here */
}

然后通过 jQuery 添加 CSS 类:

$('input[type=text]').addClass('workaround_classname');

问题是:如何确保仅当 CSS3 选择器不受本机支持时才调用此规则?

4

6 回答 6

3

为什么不设置一些无用的 css 样式并检查是否应用了样式。仅将解决方法类添加到未应用此样式的元素。

唯一的问题是我想不出一个你可以使用的“无用”风格:-)

于 2009-09-09T11:23:52.683 回答
2

这似乎包含了您所说的内容:

http://www.w3avenue.com/2009/07/02/detect-support-for-css3-html5-with-modernizr/

于 2009-09-09T11:24:38.830 回答
1

为什么不只是有

input.workaround_classname{
  /* css styling goes here */
}

然后添加workaround_classname到标记中的所有文本输入。

您可以使用的选择器是(我认为第二个可能是最容易理解它为其他阅读代码的人选择的选择器)

$('input:text')
// or
$('input:text.workaround_classname')
// or
$('input.workaround_classname')

然后不需要检测,您将不会依赖 JavaScript 来添加类名。

于 2009-09-09T12:01:41.197 回答
0

看看http://www.geocities.com/seanmhall2003/css3/detect.html。您应该为每个属性执行此操作。

于 2009-09-09T11:31:29.727 回答
0

没有简单的方法可以知道“这个浏览器是否支持 CSS3 选择器”。您所能做的就是检测浏览器和浏览器版本。

Modernizr 不会帮助您,因为您无法检测特定的 CSS 选择器是否在 .css 文件中工作。(或者您必须检查是否应用了 CSS 选择器中的特定 CSS 属性,这真的很难看!)

但!这里最简单的方法是忘记 .css 文件中的 [attr=] 之类的 CSS 2.1 选择器,因为它没有得到广泛支持。而且,如果您必须为不支持它们的浏览器(如 Internet Explorer 6)编写代码,您就无法使用它们。

因此,为每个人添加一个类。你的代码会更容易理解,否则你总是会添加不必要的 JavaScript 代码。

我知道我没有回答你,但这很糟糕!

于 2009-09-09T11:34:49.030 回答
0

我最终在我的 javascript 文件中使用了条件注释。这样我可以解决 IE6 并应用 CSS 类

$(function(){
  //add css class to input[type=text] fields if the selector is not natively supported
    // IE6 hack: Since some CSS selectors are not working, we simulate with class names.
    /*@cc_on@if (@_jscript_version <= 5.6)
    $('input[type=text],input[type=password],input[type=radio],input[type=checkbox]').
        each(function() { $(this).addClass('type_' + this.type); });
    @end@*/

});

这样,我最终为所有表单字段添加了类名:

.type_text{}
.type_radio{}
.type_checkbox{}
.type_password{}
于 2009-09-09T11:57:43.733 回答