簡體   English   中英

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

[英]set css background doesn't work in firefox

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

小提琴

在Chrome中運作良好,在IE和FF中無法運作,我缺少什么?

.css( propertyName )的jQuery文檔中:

速記CSS屬性(例如marginbackgroundborder )的檢索盡管可以在某些瀏覽器中使用,但不能保證。

看起來像在Firefox中使用window.getComputedStyle( element ) ,我相信jQuery在CSS2Properties使用它來獲取.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

使用“背景圖像”獲取圖像

$(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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM