【问题标题】:Why is document.body.style.backgroundImage name not displaying in alert? [duplicate]为什么 document.body.style.backgroundImage 名称未显示在警报中? [复制]
【发布时间】: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 对象仅具有“样式”属性中出现的内容,例如&lt;div style="width: 400px"&gt;。该示例的 style 对象 &lt;div&gt; 显示“宽度”值。

标签: javascript jquery css debugging alert


【解决方案1】:

由于您使用的是 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;
}
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案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'));
    

    【讨论】:

      猜你喜欢
      • 2011-10-17
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 2011-01-27
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      相关资源
      最近更新 更多