如何通过更改屏幕大小来更改iframe src

时间:2013-03-02 23:42:40

标签: javascript

我正在尝试根据屏幕尺寸修改链接 - 使用嵌入在iframe中的单独视频供稿用于多种预定的屏幕尺寸,因此我无法使用CSS媒体查询。

e.g。

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

修改为

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

等..

我对JavaScript不太熟悉,但我认为它是最适合这项工作的工具。这是我希望实现的代码:

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';
    }
})

我是以错误的方式接近这个吗?

2 个答案:

答案 0 :(得分:0)

您可以使用navigator.userAgent属性(可以包含“iPad”,“iPhone”等),而不是检测屏幕宽度,这样您就可以查看它是否包含这些关键字。

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

另一个例子:iPhone测试:

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

便利的网站:http://detectmobilebrowsers.com/

答案 1 :(得分:0)

也许更安全的方法是完全避免使用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>

这可能需要对使用HTML思考页面布局的方式进行一些更改,但也许最终会使事情变得更容易。