【发布时间】:2019-01-11 19:23:31
【问题描述】:
在下面的代码中
<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 -bit)) 当我刷新页面或点击“获取背景图片”按钮时。
在 Firefox 调试器中,当我单击“获取背景图像”按钮并因此点击调试器语句时,我看到 document.body.style.backgroundImage 的值为“”。
显然,我使用的是 jQuery。
注意背景图像确实显示在网页上。此外,我在调试控制台中看不到任何其他错误。还有
alert('Window is ' + width + ':' + height)
似乎输出了正确的值。
我不知道这是否相关,但我在 Rails 环境中。
我做错了什么?
【问题讨论】:
-
style对象仅包含直接在元素上设置的样式。来自 CSS 的样式将不存在。 -
我打算和其他人说的一样。您是在告诉 javascript 引入图像,但您并没有告诉 JS 在哪里可以找到该图像。它不是从 CSS 中提取它,因为您没有告诉它这样做,它不是从 javascript 中提取,因为它不知道在哪里查找。
-
@Pointy 和 Chris:谢谢你们俩。我不明白克里斯的回答。具体来说,我将如何告诉 Javascript 从 CSS 中提取?另外,请给点意见。有谁知道解释这些概念的关于 Javascript 的好书?
-
这不是真正的 JavaScript 东西;它是关于浏览器 API 以及 CSS 如何与 HTML DOM 相关的。 DOM 节点上的
style对象仅具有“样式”属性中出现的内容,例如<div style="width: 400px">。该示例的style对象<div>将显示“宽度”值。
标签: javascript jquery css debugging alert