简体   繁体   中英

Javascript screen size

Can I use some sort of JS script to take advantage of the size control here in the url?

<iframe id="myIframe" src="https://media.embed.ly/1/frame?url=http%3A%2F%2Fwww.twitch.tv%2Fgamemode_mc_&amp;width=1280&amp;height=1280&amp;secure=true&amp;key=0202f0ddb5a3458aabf520e5ab790ab9&amp;"

(My goal here is actually to place this Twitch feed as a background to my webpage - resizing the actual content of the iframe is actually a very unusual but additional treat here, because of the way Twitch's url works!)

To be clear, I'm very early in my learning of JS, and looking for a beginner solution to take the browser window size to dynamically control the parameters in this url to control the size of the content in this iframe.

width=1280&amp;height=1280&amp;

are the key lines here. I need to make these measurements follow the viewport size instead of being static. What method is best to do this?

You can certainly set the src to your iframe programmatically, and build the src url based on variables such as your viewport size.

You can try something like this:

function loadIframe() {
    var url = '',
        viewportWidth  = document.documentElement.clientWidth,
        viewportHeight = document.documentElement.clientHeight;

    url = 'https://media.embed.ly/1/frame?url=http%3A%2F%2Fwww.twitch.tv%2Fgamemode_mc_&amp;width=' + viewportWidth + '&amp;height=' + viewportHeight + '&amp;secure=true&amp;key=0202f0ddb5a3458aabf520e5ab790ab9&amp;';

    document.getElementById('myIframe').src = url;
}

Then you can make the iframe reload when the window is resized and when the window is done loading:

window.onload = loadIframe;
window.onresize = loadIframe;

However I would actually recommend using jQuery to help you do this as you would be able bind to cross-browser events easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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