javascript - 更改div背景图片,js在chrome中有效,但在ie或firefox中无效?

标签 javascript jquery internet-explorer google-chrome firefox

基本上,我希望用户能够单击并更改背景,并且对于特定的 div 有多个背景。

这在 Google Chrome 中完美运行,但在 IE 或 Firefox 中不起作用。

HTML:

<div id="palette">
<div class="lightblue"></div>
<div class="gold"></div>
<div class="aqua"></div>
</div>

<div id="primary">
</div>

CSS:

#palette {
border: 2px solid white;
width: 25px;
}

#palette div {
height: 25px;
width: 25px;
}

.lightblue { 
background: lightblue url(http://www.textureking.com/content/img/stock/big/DSC_4279.JPG); 
}

.gold { 
background: gold url(http://www.textureking.com/content/img/stock/big/DSC_4287.JPG); 
}

 .aqua { 
background: aqua url(http://www.textureking.com/content/img/stock/big/DSC_4274.JPG); 

}

JS:

$(document).ready(function() {
// attach onclick event to your palette colors
$('#palette div').on('click', function() {
    // get background of selected palette color
    var bg = $(this).css('background');
    // change the background of the body
    $('#primary').css({ 'background': bg });
}); 
});

http://jsfiddle.net/KNutQ/1/

它没有显示任何错误,并且其他 JavaScript 正在运行,所以我不太确定问题是什么。

如果很容易修复,请留下答案,如果不行我会尝试这样:http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_backgroundimage

最佳答案

根据 CSS 规范,获取速记的计算样式不应返回任何内容。您需要列出各个属性,就像我在下面所做的那样。

也许 CSS 规范或 Chrome 将来会改变,但目前 Firefox 和 IE 的行为是正确的。

$(document).ready(function() {
    // attach onclick event to your palette colors
    $('#palette div').on('click', function() {
        // get background of selected palette color
        var backgrounds = $(this).css(['background-color','background-image', 'background-repeat', 'background-attachment', 'background-position']);
         // change the background of the body
        $('body').css(backgrounds);
    }); 
});

关于javascript - 更改div背景图片,js在chrome中有效,但在ie或firefox中无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26208116/

相关文章:

javascript - 如何从 Angular 6 中的组件更新 formArray 的值

jquery - 选择 p 标签内除输入元素外的所有元素

css - 为什么我通过 -ms-filter 矩阵的偏斜没有在 IE 中应用?

css - 我们应该使用 IE 的 CSS 动态属性吗?

html - 照片网格 Internet Explorer 中不需要的底部边距

javascript - Ajax 调用在 CodeIgniter 中返回 int 而不是 string

javascript - VueJS 将属性绑定(bind)到 App.vue 中的组件

javascript - 仅通过 http 使用客户端 Javascript 访问 Dropbox 上的文件

javascript - 更新 : D3 won't draw chart data on load

jquery - 在 Internet Explorer 中使用 jquery 获取 css padding-left 的值