【发布时间】: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&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();
});
【问题讨论】:
-
[attr^=value]=> 选择具有指定属性的元素,其值正好以给定的字符串开头。我不认为正则表达式将在此工作