简体   繁体   English

如何通过更改屏幕尺寸来更改iframe src

[英]How to change iframe src with changing screen sizes

I'm attempting to modify an link based on the screen size - using separate video feeds embedded in an iframe for a number of predetermined screen sizes, so I'm unable to use CSS media-queries. 我试图根据屏幕尺寸修改链接-使用嵌入在iframe中的独立视频供稿来获取许多预定的屏幕尺寸,因此无法使用CSS媒体查询。

eg 例如

<iframe src="desktopVideoFeed.html" width="300" height="300">
</iframe>

modified to 修改为

<iframe src="mobileVideoFeed.html" width="200" height="200">
<iframe>

etc .. 等..

I'm not too familiar with JavaScript but I assume it'd be the best tool for the job. 我对JavaScript不太熟悉,但是我认为它是完成这项工作的最佳工具。 Here's the code I'm hoping to implement: 这是我希望实现的代码:

window.resize(function(){
    if(screen.width <= 480){
        document.getElementByTagName('iframe').src = 'mobileVideoFeed.html';
    }else if (screen.width <= 780){
        document.getElementByTagName('iframe').src = 'tabletVideoFeed.html';
    }else if(screen.width <= 960){
        document.getElementByTagName('iframe').src = 'desktopVideoFeed.html';
    }
})

Am I approaching this in the wrong way? 我是否以错误的方式处理此问题?

Instead of detecting the screen width, you could use the navigator.userAgent property (which can contain "iPad," "iPhone," etc., so you can check to see whether it contains these keywords. 您可以使用navigator.userAgent属性(可以包含“ iPad”,“ iPhone”等),而不是检测屏幕宽度,因此可以检查它是否包含这些关键字。

Example: mine is Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22 . 例如:我的是Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22

Another example: iPhone test: 另一个例子:iPhone测试:

if (/iPhone/i.test(navigator.userAgent)) ...

Handy site: http://detectmobilebrowsers.com/ 方便的网站: http : //detectmobilebrowsers.com/

Maybe a safer way would be to avoid the use of iframes entirely (for me they have been annoying on iOS devices several times before) and render the page differently using CSS, instead of Javascript. 也许更安全的方法是完全避免使用iframe(对我而言,它们在iOS设备上曾多次烦人),并使用CSS(而不是Javascript)以不同的方式呈现页面。

<style>
/* Main CSS here, optimized for desktop. */

@media only screen and (max-width: 780px), only screen and (max-device-width: 780px)
{
/* Optimizations for tablet screen sizes */
}

@media only screen and (max-width: 480px), only screen and (max-device-width: 480px)
{
/* Optimizations for phone screen sizes */
}
</style>

This may need some change in way of thinking about the page layout with HTML, but maybe it makes things easier eventually. 这可能需要对HTML页面布局的思考方式进行一些更改,但最终可能会使事情变得更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM