【问题标题】:background image problem with javascriptjavascript的背景图片问题
【发布时间】:2010-01-28 11:45:47
【问题描述】:

我在获取 div 的背景 url 时遇到问题

HTML:

<div id='test'></div>

CSS:

  #test { position:absolute; height:55px; width:85px; top:554px; left:197px;  background:url('images/1.jpg'); }

当我尝试使用下方获取背景图片 url 时,它显示为空白。

alert(document.getElementById("test").style.backgroundImage);

但有趣的是它适用于关注

document.getElementById("test").style.backgroundImage="url('images/1.jpg')";
alert(document.getElementById("test").style.backgroundImage);

注意: url 没有问题,因为图片显示正常

【问题讨论】:

    标签: javascript html background-image


    【解决方案1】:

    您无法从外部 CSS 获取样式信息,因为 JS 只查看 DOM。我不确定它是否可能,但是当您通过样式标记直接在元素上设置 CSS 信息时,您应该能够获取和修改它:

    <div style="position:absolute; height:55px; width:85px; top:554px; left:197px;  background:url('images/1.jpg');"></div>
    

    【讨论】:

      【解决方案2】:

      是的,这是可能的,但你总是需要这个元素:

      function getStyles (element) {
          element = document.getElementById(element);
          if (element.currentStyle) {
              return element.currentStyle;
          } else if (window.getComputedStyle) {
              return document.defaultView.getComputedStyle(element, null);
          }
      }
      

      这应该返回一个包含给定元素所有样式的关联数组。

      有趣的是,在很多情况下,无法像您尝试的那样直接从 JavaScript 访问 CSS 样式。

      【讨论】:

        猜你喜欢
        • 2015-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-12
        相关资源
        最近更新 更多