【问题标题】:Locate All YouTube iFrames by source按来源查找所有 YouTube iFrame
【发布时间】:2016-05-18 16:57:54
【问题描述】:

我正在尝试修改Fluid Width YouTube Videos script by CSS-Tricks 以使其保持最新状态。我在使用正则表达式时遇到了一些问题。

这个正则表达式有效:

  • $("iframe[src^='https://www.youtube-nocookie.com']")

这个正则表达式不起作用:

  • $("iframe[src^='\s*(https?://www.youtube(?:-nocookie)?.com/(?:v|embed)/([a-zA-Z0-9-]+).*)']")

稍后验证,所以我认为这是我如何将其放入 JS 的问题。

根据正则表达式查找 iframe 源的正确方法是什么?

HTML:

<div class="stripe">
  <div class="container">
    <div class="video-container small">
      <iframe class="video youtube" src="https://www.youtube-nocookie.com/embed/4mBqT7RcEyM?rel=0&amp;showinfo=0" frameborder="0" allowfullscreen width="530" height="298"></iframe>
    </div>
  </div>
</div>

CSS:

.stripe {
        display:table;
        margin:0px;
        padding:0px;
        width:100%;
    }
.container {
    max-width:100%;
        margin:15px auto;
        padding:15px 50px;
        background-color:#fff;
    }
.video-container {
        max-width:530px;
}

JS:

$(function() {

    // Find all YouTube videos
var $allVideos = $("iframe[src^='\s*(https?://www.youtube(?:-nocookie)?.com/(?:v|embed)/([a-zA-Z0-9-]+).*)']"),

        // The element that is fluid width
        $fluidEl = $(".video-container");

    // Figure out and save aspect ratio for each video
    $allVideos.each(function() {

        $(this)
            .data('aspectRatio', this.height / this.width)

            // and remove the hard coded width/height
            .removeAttr('height')
            .removeAttr('width');

    });

    // When the window is resized
    // (You'll probably want to debounce this)
    $(window).resize(function() {

        var newWidth = $fluidEl.width();

        // Resize all videos according to their own aspect ratio
        $allVideos.each(function() {

            var $el = $(this);
            $el
                .width(newWidth)
                .height(newWidth * $el.data('aspectRatio'));

        });

    // Kick off one resize to fix all videos on page load
    }).resize();

});

JSFiddle.

【问题讨论】:

  • [attr^=value] => 选择具有指定属性的元素,其值正好以给定的字符串开头。我不认为正则表达式将在此工作

标签: jquery regex iframe


【解决方案1】:

^= 是一个“以”开头的 jQuery 选择器,而不是正则表达式选择器。

实现这一点的最简单方法是通过src 选择所有iframe 元素和.filter 它们。

var $allVideos = $('iframe').filter(function() {
  return this.src.match(/\s*(https?:\/\/www.youtube(?:-nocookie).com\/(?:v|embed)\/([a-zA-Z0-9-]+).*)/);
});

【讨论】:

    猜你喜欢
    • 2015-04-30
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 2020-11-09
    • 2014-10-27
    • 2021-07-10
    相关资源
    最近更新 更多