最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to dynamically detect browser viewport change in size? - Stack Overflow

programmeradmin4浏览0评论

I've been having problems with scaling... automatic... dynamic... adaptive.... etc...

I have seen websites where as you make the window smaller eg. grab a corner and make the window smaller, fonts get bigger, things move around...

I've got the moving part, I don't know how to dynamically detect the browser viewport... is that a refreshing thing or?...

As you can see here, these motion things that I've used only work upon screen refresh, in particular I have a tablet, and if I visit the page in landscape, it doesn't apply; if I rotate it and then refresh, it applies.

<script language="JavaScript" type="text/javascript">
var x = screen.width;
var y = screen.height;
function scale() {
var z = x/y;
    if (z<1) {
     document.getElementById('header').style.width = "100%";
     document.getElementById('menu').style.marginLeft = "0";
     document.getElementById('menu').style.width = "20%";
     document.getElementById('menu2').style.width = "30%";
     document.getElementById('menu3').style.width = "20%";
     document.getElementById('menu4').style.width = "20%";
     document.getElementById('properties').style.width = "30%";
     document.getElementById('properties').style.marginLeft = "35%";
    }
}
scale();
</script>

This is code provided by someone from Stack Overflow regarding font, I imagine it may be similar to the direction I'm going

$( window ).resize(function() {
    $( "#container" ).css("font-size",function() {
        var value = $( "#container" ).css("width");
        console.log(parseInt(value)/24 + "pt");
        return parseInt(value)/24 + "pt";
    }) ;
});

What part is dynamic?

This console.log, I haven't used that before

Any help would be greatly appreciatedd

I've been having problems with scaling... automatic... dynamic... adaptive.... etc...

I have seen websites where as you make the window smaller eg. grab a corner and make the window smaller, fonts get bigger, things move around...

I've got the moving part, I don't know how to dynamically detect the browser viewport... is that a refreshing thing or?...

As you can see here, these motion things that I've used only work upon screen refresh, in particular I have a tablet, and if I visit the page in landscape, it doesn't apply; if I rotate it and then refresh, it applies.

<script language="JavaScript" type="text/javascript">
var x = screen.width;
var y = screen.height;
function scale() {
var z = x/y;
    if (z<1) {
     document.getElementById('header').style.width = "100%";
     document.getElementById('menu').style.marginLeft = "0";
     document.getElementById('menu').style.width = "20%";
     document.getElementById('menu2').style.width = "30%";
     document.getElementById('menu3').style.width = "20%";
     document.getElementById('menu4').style.width = "20%";
     document.getElementById('properties').style.width = "30%";
     document.getElementById('properties').style.marginLeft = "35%";
    }
}
scale();
</script>

This is code provided by someone from Stack Overflow regarding font, I imagine it may be similar to the direction I'm going

$( window ).resize(function() {
    $( "#container" ).css("font-size",function() {
        var value = $( "#container" ).css("width");
        console.log(parseInt(value)/24 + "pt");
        return parseInt(value)/24 + "pt";
    }) ;
});

What part is dynamic?

This console.log, I haven't used that before

Any help would be greatly appreciatedd

Share Improve this question asked Feb 24, 2015 at 15:07 pearlescentcrescentpearlescentcrescent 1431 gold badge3 silver badges10 bronze badges 11
  • 2 Why not use media-queries for this sort of thing? – MoshMage Commented Feb 24, 2015 at 15:08
  • 1 Media queries is the solution. – Adrian Schmidt Commented Feb 24, 2015 at 15:10
  • 1 Yes, media queries. And a css grid framework will make this even easier. – Marc Commented Feb 24, 2015 at 15:12
  • 1 @pearlescentcrescent Example Here this is using media queries, as the window gets smaller the layout "moves". – Ruddy Commented Feb 24, 2015 at 15:15
  • 1 You should used css3 media queries instead of js inline. Do all you can with css and only what you cant do on js – Pik_at Commented Feb 24, 2015 at 15:42
 |  Show 6 more ments

1 Answer 1

Reset to default 12

After reading your question and ments, I'm still a little confused, but maybe this will help.

First off, learn to use Chrome's Dev Tools. They are awesome! The most important thing you need to know for now is this:

To use console.log:

  1. In your JavaScript, write a line like console.log('Hello World!');
  2. Open that page in Google Chrome
  3. Press F12 To Toggle (Open/Close) the DevTools
  4. It will probably be on the Resources tab, this is a good place to check all your resources are loaded, but not what you're looking for.
  5. Click on the tab labeled Console
  6. Viola! You should see Hello World! if that line of JS has run.
  7. Wele to awesomsauce!

Now as to an easier visual for resize testing, try the following jQuery enhanced JavaScript: (mented for explanations, remove ments if you please)

//  This first line is the same as JavaScript's `document.ready = function() {}
//  This simply starts your code running as soon as the document is loaded and ready to go
//  It's safe to use in <head> or in <body> and will always ensure your JS is running with the page load
$(function() {
    //  Here I use .on instead of direct reference to the event as this is just good practice4 with jQuery
    //  You'll later learn you can use this with prewritten methods to "turn on/off" methods asigned to specific events
    $(window).on('resize', function(e) {
        //  Little JS Tip, No need to write `var` 50thousand times. Just use a ma and write your new variable
        var x = $(this).width(),    //  variable for window width assigned to `x`
            y = $(this).height(),   //  variable for window height assigned to `y`
            z = x/y,    //  your conversion you were using in the code you have in your question, there's plenty of different ways to test for size changes, do some Googling on "aspect ratio" as it's usually best way to go
            //  this next line is a little plicated
            //  It's assigning a variable based on result of an `inline if statement`
            //  What it says: if (element with id 'myOutput' exist) then assign that element and empty it of all it's HTML, else build the element using jQuery's element object method and append it to the <body>
            //  jQuery's element object building is easy, just remember it like this: jQuery("<tagName />", { object of attributes })
            output = $('#myOutput').length ? $('#myOutput').empty() : $('<div />', { id: 'myOutput', style: 'background: #ffa; padding: 10px; position: fixed; right: 30px; top: 30px; z-index: 999;' }).appendTo('body'),
            //  the following lines build the inner HTML for showing the results of our window dimensions
            pX = $('<p />', { text: 'x: '+x }).appendTo(output),
            pY = $('<p />', { text: 'y: '+y }).appendTo(output),
            pZ = $('<p />', { text: 'z: '+z.toFixed(5) }).appendTo(output);
    });
})

If you're using Google Chrome right now, then you can test this right now! Simply press F12 and click on Console tab. Copy the minimized code below and then click in the Console. You should see a blinking cursor ready for input. Paste the code and press enter! Then just resize the window and watch upper right! *notein upper most right you will probably see Chrome's own size box. Mine has a yellow background

Minified Code:

$(function(){$(window).on("resize",function(a){a=$(this).width();var c=$(this).height(),d=a/c,b=$("#myOutput").length?$("#myOutput").empty():$("<div />",{id:"myOutput",style:"background: #ffa; padding: 10px; position: fixed; right: 30px; top: 30px; z-index: 999;"}).appendTo("body");$("<p />",{text:"x: "+a}).appendTo(b);$("<p />",{text:"y: "+c}).appendTo(b);$("<p />",{text:"z: "+d.toFixed(5)}).appendTo(b)})});
发布评论

评论列表(0)

  1. 暂无评论