Heim  >  Artikel  >  Web-Frontend  >  jQuery(1.6.3) 中css方法对浮动的实现缺陷分析_jquery

jQuery(1.6.3) 中css方法对浮动的实现缺陷分析_jquery

WBOY
WBOYOriginal
2016-05-16 18:02:301059Durchsuche

jQuery的css方法统一了两种写法,直接使用float属性即可,如下css方法中传参数“float”即可以设置也可以获取元素的float。

复制代码 代码如下:

float div



但jQuery非要自作聪明,加上对cssFloat和styleFloat的支持,见API文档,比如获取元素的float属性时,以下是等价的。
1 $('div.left').css('float');
2 $('div.left').css('cssFloat');
3 $('div.left').css('styleFloat');
但方式3在各个浏览器中返回值不同,比如使用styleFloat获取浮动
复制代码 代码如下:

float div



元素div没有设置浮动,因此默认应该返回“none”。但结果是
IE6/7/8 : 返回空字符串"none"
IE9/Firefox/Safari/Chrome/Opera : 返回空字符串
又如使用cssFloat设置浮动:
复制代码 代码如下:

float div



IE6/7/8:设置未成功
IE9/10/Firefox/Safari/Chrome/Opera:设置成功
又如使用styleFloat设置浮动:
复制代码 代码如下:

float div



IE6/7/8/9/10/Opera:设置成功(Opera是个怪胎,styleFloat和cssFloat都支持)
Firefox/Safari/Chrome:设置不成功
因此,使用css方法获取或设置浮动时为避免各浏览器差异还是老老实实的使用float。不要使用styleFloat或cssFloat。
当然如果这算jQuery的bug,那么修复也是很容易的
1,修改jQuery.css方法,加个styleFloat的判断。
复制代码 代码如下:

// cssFloat needs a special treatment
if ( name === "cssFloat" || name === "styleFloat") {
name = "float";
}

这样使用$(xx).css("styleFloat") 就没有兼容性问题了。
2,修改jQuery.style方法,加个判断如果传styleFloat或cssFloat都转成float
复制代码 代码如下:

// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// 这是加的修复代码
if( name === "cssFloat" || name === "styleFloat" ) {
name = "float"
}
// Make sure that we're working with the right name
var ret, type, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];

这样使用$(xx).css("cssFloat", "right") 或 $(xx).css("styleFloat", "right") 各浏览器就都ok了。
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn