Change iframe width and height using jQuery?

2020-02-13 08:06发布

问题:

I have tried a solution that I found on this website. However, it did not work for me. I am thinking there is a script that is setting this somewhere else so I need to add some code in the page to overide the style.

I tried this:

<script type="text/javascript">
    $(document).ready(function () {
        $("#frame1").width(578);
        $("#frame1").height(326);
    });
</script>

However, the html still comes out like this:

<iframe frameborder="0" src="http://player.vimeo.com/video/20657168?color=fc030f" style="width: 500px; height: 281.25px;"></iframe>

I want the width to be 578 and the height to be 326. Here is the website: http://beckindesigns.tumblr.com/

P.S. If I add a class or ID it strips it from the html. I am using Tumblr..

回答1:

It will work if you add id="frame1" to your iframe.

<iframe frameborder="0" id="frame1" src="http://player.vimeo.com/video/20657168?color=fc030f" style="width: 500px; height: 281.25px;"></iframe>

The $("#frame1") will select the element with the id attribute frame1. For reference: jQuery Selectors and ID Selector.

Update: Since you said that the ID is getting stripped out, you can just change how the selector is working, and apply it to all iFrames:

<script type="text/javascript">
    $(document).ready(function () {
        $("iframe").width(678);
        $("iframe").height(526);
    });
</script>

If you have multiple iFrames on page and you don't want them to be the same size, you can use the :eq(index) selector, which will match on the zero-based index. So if you have two iFrames on the page, and only want to change the second, use:

<script type="text/javascript">
    $(document).ready(function () {
        $("iframe:eq(1)").width(678);
        $("iframe:eq(1)").height(526);
    });
</script>


回答2:

Adjust iframe to window size

<iframe frameborder="0" src="http://player.vimeo.com/video/20657168?color=fc030f" style="width: 500px; height: 281.25px;"></iframe>

<script>
    $(document).ready(function(){
       $("iframe").height($(window).height());
       $("iframe").width($(window).width());

       $( window ).resize(function() {
            $("iframe").height($(window).height());
            $("iframe").width($(window).width());
        });
    });
  </script>