如何使用Javascript而不是Jquery将Image Source设置为div / img background-image?

时间:2017-02-24 17:41:08

标签: javascript image background-image src

如何在JavaScript中执行此操作?

带百分比的高度不适用于chrome,而且这也不适用于IE 5仿真。

我想知道我们是否可以使用JavaScript获得相同的结果,并且还使高度100%在chrome和IE 5仿真中工作?

$(function() {
    $("button").click(function() {
        $("img").each(function(i, elem) {
            var img = $(elem);
            var processing = $(this).attr("src");
            var div = $("<div />").css({
                "backgroundImage": "url(" + processing + ")",
                width: "100%",
                height: "100%",
            });

            div.html(img.attr("alt"));
            div.addClass("replacedImage");

            img.replaceWith(div);
        });
    });
});

这是我正在寻找的东西,但我们怎样才能用javascript做同样的事情?

Fiddle Example

angular.
module('myApp', []).
directive('myBackgroundImage', function() {
  return function(scope, element, attrs) {
    element.css({
      'background-image': 'url(' + attrs.myBackgroundImage + ')',
      'background-size': 'cover',
      'background-repeat': 'no-repeat',
      'background-position': 'center center'
    });
  };
});
div.wide {
  width: 200px;
  height: 100px;
  border: 1px solid orange;
}

div.tall {
  width: 100px;
  height: 200px;
  border: 1px solid orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div>
    <h2>Vanilla Image:</h2>
    <img src="http://images2.wikia.nocookie.net/__cb20110811172434/fallingskies/images/f/fd/Totoro_normal.gif" />
  </div>

  <div>
    <h2>Fill 200x100</h2>
    <div class="wide" my-background-image="http://images2.wikia.nocookie.net/__cb20110811172434/fallingskies/images/f/fd/Totoro_normal.gif"></div>
  </div>
  <div>
    <h2>Fill 100x200</h2>
    <div class="tall" my-background-image="http://images2.wikia.nocookie.net/__cb20110811172434/fallingskies/images/f/fd/Totoro_normal.gif"></div>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

这是一个纯粹的CSS解决方案。

div.wide {
    width: 200px;
    height: 100px;
    border: 1px solid orange;
    background:  url("http://images2.wikia.nocookie.net/__cb20110811172434/fallingskies/images/f/fd/Totoro_normal.gif") center center;
    background-size: cover;
}

div.tall {
    width: 100px;
    height: 200px;
    border: 1px solid orange;
    background: url("http://images2.wikia.nocookie.net/__cb20110811172434/fallingskies/images/f/fd/Totoro_normal.gif") center center no-repeat;
    background-size: cover;
}
<div ng-app="myApp">
    <div>
        <h2>Vanilla Image:</h2>
        <img src="http://images2.wikia.nocookie.net/__cb20110811172434/fallingskies/images/f/fd/Totoro_normal.gif" />
    </div>
    
    <div>
        <h2>Fill 200x100</h2>
        <div class="wide"></div>
    </div>
    <div>
        <h2>Fill 100x200</h2>
        <div class="tall"></div>
    </div>
</div>