【问题标题】:How to set manual default image, if image is not available on my site using js?如果使用 js 在我的网站上没有图像,如何设置手动默认图像?
【发布时间】:2014-10-12 02:55:08
【问题描述】:

如果网站上没有特定图像,我想设置手动虚拟图像。另外如何设置该图像是否在服务器上被删除或不可用,在这种情况下我还需要使用 JS 显示默认图像。

【问题讨论】:

  • 如@Axel指出的,请更新问题状态

标签: javascript image angularjs


【解决方案1】:

你可以试试:

function imgError(image) {
    image.onerror = "";
    image.src = "/images/noimage.gif";
    return true;
}
<img src="image.png" onerror="imgError(this);"/>

或:

$("img").error(function () {
  $(this).unbind("error").attr("src", "broken.gif");
});

【讨论】:

  • 您的第二个示例存在时间问题:error 事件可能在您挂钩之前 已触发。
  • setTimeout 对代码运行之前发生的事件没有帮助。
【解决方案2】:

这是跨浏览器,原版 JavaScript 并且没有任何丑陋的 onerror="" 标记:

var sPathToDefaultImg = 'http://lorempixel.com/150/100/abstract/2/Placeholder/';

var replaceImageWithPlaceholderIfNotAvail = function( domImg ) {

  // sanitize domImg
  if ( !domImg || !domImg.nodeName || domImg.nodeName != 'IMG' ) {
    // get all images from DOM
    aImg = document.getElementsByTagName('IMG');
    i    = aImg.length;
    if ( i ) {
      while ( i-- ) {
        replaceImageWithPlaceholderIfNotAvail( aImg[i] );
      }
    }
    return;
  }

  // here is where the magic happens
  oImg         = new Image();       // create new Image
  oImg.onerror = function() {       // assign onerror
    domImg.src = sPathToDefaultImg; // handler function
  };
  oImg.src     = domImg.src;        // set src of new Image

};

// now you can use the function on "auto pilot"
replaceImageWithPlaceholderIfNotAvail()

// or feed with any domImage you like to evaluate
// replaceImageWithPlaceholderIfNotAvail( domCustomImg )
Available: <img src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo-med.png" alt="notavail1.jpg"><br>

Not Available: <img src="notavail1.jpg" alt="notavail2.jpg"><br>

Available: <img src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo-med.png" alt="notavail1.jpg"><br>

Not Available: <img src="notavail2.jpg" alt="notavail4.jpg">

CODEPEN:

【讨论】:

    【解决方案3】:

    您可以采用以下方法:

    var $defaultImage = '...location of default image..';
    

    然后在加载之前使用三元运算符检查图像:

    var $src = empty($src) ? $src : defaultImage; // dummy code 
    

    或创建一个函数,如果图像不存在,将检查并返回默认图像:

    checkImageExist($loc)  {
        check for $loc 
        if $loc is undefined or null then return $defaulImage
    }
    

    【讨论】:

      【解决方案4】:

      更新:这是此答案的自定义指令版本。我相信这是最好的“角度”方法。它仍然取决于原始答案中定义的服务:

      app.directive('imageOrDefault', function (Utils) {
          return {
              restrict: 'A',
              link: function (scope, element, attrs) {
                  console.log(attrs);
                  Utils.isImage(attrs.imageOrDefault).then(function(result) {
                      attrs.$set('src', result);
                  });
              }
          }
      });
      

      您可以在标记中使用它,如下所示:

      <img image-or-default="http://r.llb.be/img/search-418.png" height="42" width="42">
      

      Here is a plunkr of this version.


      初步回答

      您可以使用 ng-src 指令来执行此操作,并使用服务来测试图像是否确实存在。 Here is an example of working plunkr 您可以根据自己的具体需求进行调整。

      有一个isImage() 函数将测试一个URL 并返回一个promise。如果 URL 是有效的图像路径,则 promise 是带有该 URL 的 resolved。如果不是,promise 将是 resolved 与您的默认图像路径。

      app.factory('Utils', function($q) {
          return {
              isImage: function(src) {
                  var deferred = $q.defer();
                  var image = new Image();
                  image.onerror = function() {
                      deferred.resolve('yourDefaultImagePath');
                  };
                  image.onload = function() {
                      deferred.resolve(image.src);
                  };
                  image.src = src;
      
                  return deferred.promise;
              }
          };
      });
      

      在标记中,我使用ng-src-directive 等待promiseresolve,然后再设置src-属性。

      <img ng-src="{{result}}" height="42" width="42">
      

      isImage() 函数是从 controller 调用的:

      app.controller('MainCtrl', function($scope, Utils) {
          $scope.test = function() {
              Utils.isImage($scope.source).then(function(result) {
                  console.log(result);
                  $scope.result = result;
              });
          };
      });
      

      此解决方案可以轻松适应自定义指令。如果您对这种方法感兴趣,请告诉我。

      解决方案改编自:Angular js - isImage( ) - check if it's image by url

      【讨论】:

      • 我已经完成了答案。 rgds
      • 所以你只发布“你可以使用 ng-src 指令来做到这一点”。然后在 40 多分钟后回来写一个有用的答案?应有的尊重,下次我会等到你能发布一些有用的东西。
      • 你是对的。对此感到抱歉。我在智能手机上,然后回来使用真正的键盘正确回答。
      • 因此,这是通过主动将图像加载到单独的 Image 对象中来工作的,然后如果成功,则将相同的源分配给目标图像,否则使用默认图像。整洁的!但是......图像路径来自哪里?原来,我的意思是?该代码似乎正在使用$scope.source(它传递给isImage,它使用它作为src)。这是哪里来的?
      • 如果您查看 plunkr,它来自“输入”。我将使用自定义指令更新答案,我认为这是更清洁的解决方案。
      猜你喜欢
      • 2016-10-20
      • 1970-01-01
      • 2012-01-31
      • 2021-10-23
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 2012-11-10
      • 1970-01-01
      相关资源
      最近更新 更多