javascript - 设置 css 背景在 firefox 中不起作用

标签 javascript jquery css

$(function () {
    var getBg = $('.one').css('background');
    $('.two').css('background', getBg);
});

Fiddle

在 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-imagebackground-position 等)都可以。其他简写属性可能也一样,例如font 是空字符串,而font-familyfont-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/

相关文章:

javascript - 在javascript中对两个值求和

javascript - 上下文菜单不适用于新内容

javascript - 防止表单在 jQuery Validate 插件的 submitHandler 函数中提交

javascript - 如何打印动态生成的pdf dataUrl?

javascript - 如何从字符串中拆分 key 对等值?

javascript - Fabric js 从缺少属性的 url 加载 svg

javascript - jQuery .bind() 选择器

javascript - 过渡分区不工作

javascript - JQuery 动画和 slideUp 同时

html - 带边框的 div 内的表格不占用全部空间