在以下代码中
<style>
/* Set height to 100% for body and html to enable the background image to cover the whole page: */
body, html {
height: 100%
}
body {
background-image: url('/assets/root/001.png');
// background-size: contain;
// background-position: center;
background-size: 786px 594px;
// background-size: 1920px 933px;
background-repeat: no-repeat;
}
</style>
<div>
<h1>Some message</h1>
<button type="button" onclick="myFunction()">Get background image</button>
<script>
function myFunction() {
debugger;
alert(document.body.style.backgroundImage);
}
</script>
<script language="JavaScript" type="text/javascript">
var width = $(window).width();
var height = $(window).height();
/* debugger; */
alert(document.body.style.backgroundImage);
alert('Window is ' + width + ':' + height)
</script>
</div>
我希望
alert(document.body.style.backgroundImage);
显示类似'/assets/root/001.png'的内容,但该警告在Firefox(61.0.1(64位))和Chrome(版本68.0.3440.84(官方内部版本)(64位)),无论是刷新页面还是单击“获取背景图片”按钮。
在Firefox调试器中,当我单击“获取背景图像”按钮并点击调试器语句时,我看到document.body.style.backgroundImage的值为“”。
很明显,我正在使用jQuery。
背景图像确实显示在网页上。另外,我在调试控制台中看不到任何其他错误。还有
alert('Window is ' + width + ':' + height)
似乎输出正确的值。
我不知道这是否相关,但是我在Rails环境中。
我在做什么错了?
答案 0 :(得分:3)
由于您使用的是jQuery,因此您可以通过以下方式获得样式:
$('body').css('backgroundImage')
即使元素仅在样式表中声明,jQuery也会获得元素的计算样式。
console.log($('body').css('backgroundImage'));
body {
background-image: url('/assets/root/001.png');
background-size: 786px 594px;
background-repeat: no-repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 1 :(得分:2)
@Pointy是正确的,style
仅指代内联样式。应用样式表等后,您可以使用window.getComputedStyle(document.body)
获取所有样式:
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
类似的事情可能会做:
alert(window.getComputedStyle(document.body).getPropertyValue('background-image'));