开发者

getting all iFrames within a div and resizing them for mobile

In short, the problem is this: we have a news site that has a mobile version of the website. For the page that displays whatever article is called, occasionally, there are embedded videos (from youtube) that show up in iframes. T开发者_高级运维heir default size is typically something like 580px, which obviously comes out far too big and wide on a mobile browser.

I wanted to use javascript to search the content and resize any iframe as it finds it. That said, I don't know if using JavaScript on mobile will be the best thing to do, and second, I'm not sure how to search for all instances of a certain element type like that. The iframes do not come in with names or IDs...

I briefly considered using PHP to search for <iframe but it seems that php, in this instance, would be unnecessarily sloppy and potentially easily broken.

Does anybody have advice/suggestions on how to handle this problem?


Using jQuery it's very easy to select elements based on tag.

jQuery:

$('iframe').width(300);

Fairly easy using normal DOM as well.

var iframes = document.getElementsByTagName('iframe');
    for (var i=0; i<iframes.length; i++)
    {
      iframes[i].style.width = "300px"
    }


Using jQuery, resizing all iframes on a document would be as simple as typing, for example,

$('iframe').css('width', '200px');

Sure, jQuery has an overhead in terms of size, but minified and gzipped, its footprint is not so large, even for mobile applications.


This worked for me:

Just include the width margin you want at the top:

//Just Change this
var margin = "20";
//////////////////////////////////////////////////////
var iframes = document.getElementsByTagName('iframe');
var w = window.innerWidth || document.body.clientWidth;
var newwidth = w - ( 2 * margin );

for (var i=0; i<iframes.length; i++)
{
 var currentheight = iframes[i].height;
 var currentwidth  = iframes[i].width;  
 var newheight = (newwidth / currentwidth) * currentheight;

  iframes[i].style.width = newwidth+"px";
  iframes[i].style.height = newheight+"px";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜