【问题标题】:Change div background image, js works in chrome but not ie or firefox?更改div背景图像,js在chrome中工作,但不是ie或firefox?
【发布时间】:2014-10-05 23:02:07
【问题描述】:

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

这在谷歌浏览器中完美运行,但在 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/

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

如果容易解决,请留下答案,否则我会这样尝试:http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_backgroundimage

【问题讨论】:

  • 嗯,也许可以创建一个 cookie 来记住他们选择的背景?

标签: javascript jquery internet-explorer google-chrome firefox


【解决方案1】:

根据 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);
    }); 
});

【讨论】:

    猜你喜欢
    • 2015-04-04
    • 2015-07-11
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多