我正在尝试修改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&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();
});
答案 0 :(得分:1)
^=
是&#34;以&#34;开头jQuery选择器,而不是正则表达式选择器。
实现此目标的最简单方法是按iframe
选择所有.filter
元素和src
元素。
var $allVideos = $('iframe').filter(function() {
return this.src.match(/\s*(https?:\/\/www.youtube(?:-nocookie).com\/(?:v|embed)\/([a-zA-Z0-9-]+).*)/);
});