我有2种不同屏幕宽度的2种不同的YouTube视频。
我想动态地加载每个视频,特别是在访问者达到该屏幕尺寸时,而不是在加载文档时加载它们。
<div id="size1000">
<iframe width="250" height="250" src="https://www.youtube.com/embed/tR-5AZF9zPI" frameborder="0" allowfullscreen></iframe>
</div>
<div id="size500">
<iframe width="200" height="200" src="https://www.youtube.com/embed/tR-K69A1lL1PHQ" frameborder="0" allowfullscreen></iframe>
</div>
的CSS
#size1000, #size500{
display:none;
}
@media(width:1000px){
#size1000{
display:block;
}
}
@media(width:500px){
#size500{
display:block;
}
}
这可能吗?如果是这样,这是怎么做的?
最佳答案
由于我误解了您的要求,因此以下是一个简单的示例,该示例使用Javascript检测客户端宽度并根据屏幕尺寸显示适当的YouTube标签(如果有)。
Here's another Plunk。每次更改帧宽度后,您将需要停止并重新运行它,这与带有媒体查询的示例不同。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<script>
if (document.body.clientWidth >= 1000) {
document.write('<iframe width="250" height="250" src="https://www.youtube.com/embed/tR-5AZF9zPI" frameborder="0" allowfullscreen></iframe>');
} else if (document.body.clientWidth >= 500) {
document.write('<iframe width="200" height="200" src="https://www.youtube.com/embed/tR-K69A1lL1PHQ" frameborder="0" allowfullscreen></iframe>');
}
</script>
</body>
</html>
这不能处理显示尺寸的动态变化,例如方向变化。您必须挂接到事件上才能做到这一点。但是它向您展示了基础知识。
更新:这是处理屏幕调整大小事件的基本形式。这里应该有很多问题要解决。
window.onresize = function(event) {
...
};
我希望这就是你的意思。如果没有,我放弃。 ;)