基本上,我希望用户能够单击并更改背景,并且对于特定的 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 });
});
});
它没有显示任何错误,并且其他 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/