我正在尝试使所有嵌入视频响应,因为我找不到使用 bootstrap 3 使视频响应的良好解决方案。使用下面的代码我可以使任何视频响应。但我想在下面的代码中添加 If 条件,以便在调整窗口大小时,代码仍然可以完成这项工作。
我的jquery代码:
$(document).ready(function(){
function show(){
var containerWidth = $(".col-video").width();
$('iframe').each(function(){
var iframeWidth = $(this).attr("width");
var iframeHeight = $(this).attr("height");
var flag = containerWidth / iframeWidth;
var newHeight = iframeHeight * flag;
$(this).attr("width", "100%");
$(this).attr("height", newHeight);
});
$('video').each(function(){
var videoWidth = $(this).attr("width");
var videoHeight = $(this).attr("height");
var flag = containerWidth / videoWidth;
var newHeight = videoHeight * flag;
$(this).attr("width", "100%");
$(this).attr("height", newHeight);
});
}
show();
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<link href="bootstrap.min.css" rel="stylesheet">
<link href="style.css" rel="stylesheet">
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-video">
<h1>Hello World</h1>
<iframe width="560" height="315" src="https://www.youtube.com/embed/kIsscNG9Q54" frameborder="0" allowfullscreen></iframe>
<iframe src="https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fskillinprogramming%2Fvideos%2F1356766841067995%2F&show_text=0&width=400" width="400" height="400" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true" allowFullScreen="true"></iframe>
<video src="video.mp4" controls></video>
</div>
</div>
</div>
<script src="jquery.min.js"></script>
<script src="bootstrap.min.js"></script>
<script src="test.js"></script>
</body>
</html>
最佳答案
您可以在窗口调整大小事件中运行代码,因为该事件连续触发,您可以使用去抖动函数,例如:
var myEfficientFn = debounce(function() {
show();
}, 250);
$(window).on('resize', myEfficientFn);
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
关于javascript - 如何在 jquery 中向 $(window).resize 事件添加 if 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44617175/