javascript - 如果原始 src 的高度/宽度小于 "x"像素,是否更改图像 src?

标签 javascript jquery youtube append src

如果原始 src 的比例缩小了“x”像素(宽度/高度),是否可以检索替代图像 src 来代替另一个图像 src?

为了更具描述性,我正在开发一个脚本,该脚本将高质量缩略图覆盖在视频 iframe 上。对于高清格式的视频(例如 720p 和 1080p),它们返回全尺寸的 maxresdefault 缩略图。

但是,对于非高清格式的视频(小于 720p 分辨率的视频),它们会生成非常小的 maxresdefault.jpg 图像,我更愿意将其替换为 hqdefault.jpg 缩略图代替。

这是我当前正在使用的脚本的片段:

;
(function($, window, document, undefined) {

  "use strict";

  var defaults = {
    darkenThumbnail: false
  };

  function YouTubeHDThumbnail(element, options) {
    this.elem = element;
    this.$elem = $(element);
    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = 'youTubeHDThumbnail';
    this.init();
  }

  $.extend(YouTubeHDThumbnail.prototype, {
    init: function() {
      this.videoId = null,
        this.$thumbnail = null;

      // retrieve HD thumbnail
      var src = this.$elem.attr('src'),
        srcSplit = src.split('?'),
        srcMain = null,
        srcPure = null;

      if (srcSplit.length > 0) {
        srcMain = srcSplit[0];
        srcPure = srcMain.split('/');
        this.videoId = srcPure.pop();
        this.$thumbnail = $('<a />')
          .attr({
            'href': '#'
          })
          .addClass('yt-hd-thumbnail')
          .append(
            $('<img/>').attr({
              'src': 'http://i.ytimg.com/vi/' + this.videoId + '/maxresdefault.jpg'
            })
          );
      } else {
        console.log('The src attribute of iframe is not valid.');
        return;
      }

      // create container
      var $outerContainer = $('<div />')
        .addClass('yt-hd-thumbnail-outer-container')
        .insertAfter(this.elem)
        .css('width', this.$elem.attr('width')),

        $innerContainer = $('<div />')
        .addClass('yt-hd-thumbnail-inner-container')
        .appendTo($outerContainer);

      // insert thumbnail and iframe
      if (this.settings.darkenThumbnail) {
        this.$thumbnail.addClass('yt-hd-thumbnail-darken');
      }
      $innerContainer.append(this.$thumbnail).append(this.elem);


      // add click handler to thumbnail
      var self = this;
      this.$thumbnail.on('click', function(e) {
        e.preventDefault();
        src = src + '&autoplay=1';
        $innerContainer.addClass('yt-hd-thumbnail-clicked');
        self.$elem.attr({
          'src': src
        });
      });
    },
  });

  $.fn['youTubeHDThumbnail'] = function(options) {
    return this.each(function() {
      if (!$.data(this, "plugin_" + 'youTubeHDThumbnail')) {
        $.data(this, "plugin_" +
          'youTubeHDThumbnail', new YouTubeHDThumbnail(this, options));
      }
    });
  };

})(jQuery, window, document);

/* YouTube HD Thumbnails / Add HD Class */
$(document).ready(function() {
  $('iframe[src*="youtube.com"]').addClass("yt-hd-thumbnail");
});

/* YouTube HD Thumbnails / Thumbnail Hover Effect */
$(document).ready(function() {
  $('iframe.yt-hd-thumbnail').youTubeHDThumbnail({
    darkenThumbnail: true
  });
});
.yt-hd-thumbnail-inner-container {
  height: 0;
  padding-top: 56.25%;
  position: relative
}

.yt-hd-thumbnail-inner-container>a.yt-hd-thumbnail,
.yt-hd-thumbnail-inner-container>iframe {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-width: 0
}

.yt-hd-thumbnail-inner-container>a.yt-hd-thumbnail {
  z-index: 2
}

.yt-hd-thumbnail-inner-container>a.yt-hd-thumbnail img {
  width: 100%
}

.yt-hd-thumbnail-inner-container>a.yt-hd-thumbnail.yt-hd-thumbnail-darken:before {
  display: block;
  position: absolute;
  content: '';
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
  opacity: .3;
  -webkit-transition: opacity .3s ease;
  -moz-transition: opacity .3s ease;
  transition: opacity .3s ease
}

.yt-hd-thumbnail-inner-container>a.yt-hd-thumbnail.yt-hd-thumbnail-darken:hover:before {
  opacity: 0
}

.yt-hd-thumbnail-inner-container>iframe {
  max-width: 100%;
  opacity: 0;
  -webkit-transition: opacity .3s ease .3s;
  -moz-transition: opacity .3s ease .3s;
  transition: opacity .3s ease .3s
}

.yt-hd-thumbnail-inner-container.yt-hd-thumbnail-clicked>a.yt-hd-thumbnail {
  display: none
}

.yt-hd-thumbnail-inner-container.yt-hd-thumbnail-clicked>iframe {
  opacity: 1
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<b>Video with a Max Resolution of: 480p</b>
<br>
<iframe width="560" height="315" src="https://www.youtube.com/embed/QgfxdTnLdt4?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

<br>

<b>Video with a Max Resolution of: 1080p</b>
<br>
<iframe width="560" height="315" src="https://www.youtube.com/embed/fPj-mEFPhrA?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

最佳答案

这似乎有效:

/*... */
const thumb = $('<img/>', {
  src: 'http://i.ytimg.com/vi/' + this.videoId + '/maxresdefault.jpg'
});
thumb.on('load', () => {
  const src = thumb[0].width < 121 ?
    'https://cdn.pixabay.com/photo/2015/06/19/17/58/sample-815141_960_720.jpg' :
    'http://i.ytimg.com/vi/' + this.videoId + '/maxresdefault.jpg';
  this.$thumbnail.append( $('<img/>',{src}) );
});
/*... */

;
(function($, window, document, undefined) {

  "use strict";

  var defaults = {
    darkenThumbnail: false
  };

  function YouTubeHDThumbnail(element, options) {
    this.elem = element;
    this.$elem = $(element);
    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = 'youTubeHDThumbnail';
    this.init();
  }

  $.extend(YouTubeHDThumbnail.prototype, {
    init: function() {
      this.videoId = null,
        this.$thumbnail = null;

      // retrieve HD thumbnail
      var src = this.$elem.attr('src'),
        srcSplit = src.split('?'),
        srcMain = null,
        srcPure = null;

      if (srcSplit.length > 0) {
        srcMain = srcSplit[0];
        srcPure = srcMain.split('/');
        this.videoId = srcPure.pop();
        this.$thumbnail = $('<a />')
          .attr({
            'href': '#'
          })
          .addClass('yt-hd-thumbnail')
          
          const thumb = $('<img/>', {
            src: 'http://i.ytimg.com/vi/' + this.videoId + '/maxresdefault.jpg'
          });
          thumb.on('load', () => {
            const src = thumb[0].width < 121 ?
               'https://cdn.pixabay.com/photo/2015/06/19/17/58/sample-815141_960_720.jpg':
               'http://i.ytimg.com/vi/' + this.videoId + '/maxresdefault.jpg';
            this.$thumbnail.append(
              $('<img/>',{src})
            );
          });
          
      } else {
        console.log('The src attribute of iframe is not valid.');
        return;
      }

      // create container
      var $outerContainer = $('<div />')
        .addClass('yt-hd-thumbnail-outer-container')
        .insertAfter(this.elem)
        .css('width', this.$elem.attr('width')),

        $innerContainer = $('<div />')
        .addClass('yt-hd-thumbnail-inner-container')
        .appendTo($outerContainer);

      // insert thumbnail and iframe
      if (this.settings.darkenThumbnail) {
        this.$thumbnail.addClass('yt-hd-thumbnail-darken');
      }
      $innerContainer.append(this.$thumbnail).append(this.elem);


      // add click handler to thumbnail
      var self = this;
      this.$thumbnail.on('click', function(e) {
        e.preventDefault();
        src = src + '&autoplay=1';
        $innerContainer.addClass('yt-hd-thumbnail-clicked');
        self.$elem.attr({
          'src': src
        });
      });
    },
  });

  $.fn['youTubeHDThumbnail'] = function(options) {
    return this.each(function() {
      if (!$.data(this, "plugin_" + 'youTubeHDThumbnail')) {
        $.data(this, "plugin_" +
          'youTubeHDThumbnail', new YouTubeHDThumbnail(this, options));
      }
    });
  };

})(jQuery, window, document);

/* YouTube HD Thumbnails / Add HD Class */
$(document).ready(function() {
  $('iframe[src*="youtube.com"]').addClass("yt-hd-thumbnail");
});

/* YouTube HD Thumbnails / Thumbnail Hover Effect */
$(document).ready(function() {
  $('iframe.yt-hd-thumbnail').youTubeHDThumbnail({
    darkenThumbnail: true
  });
});
.yt-hd-thumbnail-inner-container {
  height: 0;
  padding-top: 56.25%;
  position: relative
}

.yt-hd-thumbnail-inner-container>a.yt-hd-thumbnail,
.yt-hd-thumbnail-inner-container>iframe {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-width: 0
}

.yt-hd-thumbnail-inner-container>a.yt-hd-thumbnail {
  z-index: 2
}

.yt-hd-thumbnail-inner-container>a.yt-hd-thumbnail img {
  width: 100%
}

.yt-hd-thumbnail-inner-container>a.yt-hd-thumbnail.yt-hd-thumbnail-darken:before {
  display: block;
  position: absolute;
  content: '';
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
  opacity: .3;
  -webkit-transition: opacity .3s ease;
  -moz-transition: opacity .3s ease;
  transition: opacity .3s ease
}

.yt-hd-thumbnail-inner-container>a.yt-hd-thumbnail.yt-hd-thumbnail-darken:hover:before {
  opacity: 0
}

.yt-hd-thumbnail-inner-container>iframe {
  max-width: 100%;
  opacity: 0;
  -webkit-transition: opacity .3s ease .3s;
  -moz-transition: opacity .3s ease .3s;
  transition: opacity .3s ease .3s
}

.yt-hd-thumbnail-inner-container.yt-hd-thumbnail-clicked>a.yt-hd-thumbnail {
  display: none
}

.yt-hd-thumbnail-inner-container.yt-hd-thumbnail-clicked>iframe {
  opacity: 1
}
.yt-hd-thumbnail-inner-container a {
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<b>Video with a Max Resolution of: 480p</b>
<br>
<iframe width="560" height="315" src="https://www.youtube.com/embed/QgfxdTnLdt4?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

<br>

<b>Video with a Max Resolution of: 1080p</b>
<br>
<iframe width="560" height="315" src="https://www.youtube.com/embed/fPj-mEFPhrA?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

我做了什么:

  • 我删除了 .append($('<img />')...)部分。
  • 相反,我放置了 <img>变量中的元素并等待它加载。
  • load发生该 img 的事件时,我检查其宽度。如果小于121 ,我设置了src到我漂亮的照片。如果没有,我会传递原始的(它已经加载,因此被缓存)。
  • 我 append <img>this.$thumnail .

121来自像素化缩略图的宽度为120px的事实.

关于javascript - 如果原始 src 的高度/宽度小于 "x"像素,是否更改图像 src?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51774781/

相关文章:

javascript - Ajax 脚本不起作用

javascript - 无法读取未定义的属性 'setState'

javascript - 如何使用 Javascript 中的函数访问对象的属性值?

javascript - 如何等待 jQuery ajax 请求循环完成?

javascript - DataTables 无法重新初始化或需要插件

android - Android Webview 中的 Youtube 直播流很紧张

javascript - 如何避免 $http 请求后重复 .then() 和 .catch() ?

javascript - 使用 jquery 重新排序 HTML 表中的列

python - 使用youtube_dl提取信息时出错

filter - 如何过滤不当的youtube视频?