$(function () {
var getBg = $('.one').css('background');
$('.two').css('background', getBg);
});
在 Chrome 中运行良好,在 IE 和 FF 中不起作用,我错过了什么?
最佳答案
来自关于 .css( propertyName )
的 jQuery 文档:
Retrieval of shorthand CSS properties (e.g.,
margin
,background
,border
), although functional with some browsers, is not guaranteed.
它看起来像在 Firefox 中使用 window.getComputedStyle( element )
,我相信 jQuery 在后台使用它来获取 .css('property')
[ 1],返回一个 CSS2Properties
集合,其中 background
属性是一个空字符串。但所有更具体的背景相关属性(如 background-image
、background-position
等)都可以。其他简写属性可能也一样,例如font
是空字符串,而font-family
、font-size
等有值。
您可以通过一个一个地克隆这些属性来修复它:
http://jsfiddle.net/ohvuLqwe/5/
$(function () {
// get a reference to original element
var original = document.querySelector('.one');
// get the computed style
var styleprops = getComputedStyle( original );
// create an object to hold the relevant properties
var clonebg = {};
// iterate over the computed properties...
for( var prop in styleprops ){
// and store them in the object if they are not empty and the name starts with "background"
if( prop.indexOf('background') == 0 && styleprops[prop] != "" ){
clonebg[ prop ] = styleprops[prop];
}
}
// use the jQuery .css({}) method to set all the cloned properties.
$('.two').css(clonebg );
});
[1] https://github.com/jquery/jquery/blob/master/src/css/var/getStyles.js
关于javascript - 设置 css 背景在 firefox 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29510910/