设置 CSS 背景在 Firefox 中不起作用

set css background doesn't work in firefox

本文关键字:不起作用 Firefox CSS 背景 设置      更新时间:2023-09-26
$(function () {
    var getBg = $('.one').css('background');
    $('.two').css('background', getBg);
});

小提琴

在Chrome中运行良好,在IE和FF中不起作用,我缺少什么?

来自 jQuery 文档 .css( propertyName )

检索速记 CSS 属性(例如,marginbackgroundborder (,尽管在某些浏览器中可以正常工作,但不能保证。

看起来在 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

使用"background-image"获取图像

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

小提琴

尝试使用background-image属性

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

小提琴

试试

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