如何动态检测浏览器视口大小的变化? [英] How to dynamically detect browser viewport change in size?

查看:448
本文介绍了如何动态检测浏览器视口大小的变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直遇到缩放问题...自动...动态...自适应....等等...



我见过网站当你使窗口变小时,例如。抓住一个角落,让窗口变小,字体变大,东西移动......



我有移动部分,我不知道如何动态检测浏览器视口...是一个令人耳目一新的事情或?...

正如你在这里看到的,这些动作我只用在屏幕上刷新,特别是我有一台平板电脑,如果我访问横向页面,它不适用;如果我旋转它然后刷新,它适用。

 < script language =JavaScripttype =text / javascript> 
var x = screen.width;
var y = screen.height;
函数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>

这是由Stack Overflow提供的关于字体的代码,我想它可能类似于方向我要去

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

什么部分是动态的?



console.log,我之前没有用过

任何帮助都会大大增益

解决方案

在阅读你的问题和评论后,我仍然有点困惑,但也许这会有所帮助。 首先,学习使用< Chrome的开发工具。他们是 真棒 !您现在需要知道的最重要的事情是:



使用 console.log


  1. 在你的JavaScript中,写一行如 console.log('Hello World!');

  2. Google Chrome

  3. F12 切换(打开/关闭)DevTools
  4. 它可能位于 Resources 选项卡上,这是一个检查所有资源已加载的好地方,但不是您要查找的内容。

  5. 点击标签控制台

  6. 中提琴!您应该看到 Hello World!,如果该行的JS已经运行。

  7. 欢迎来到awesomsauce!

现在,为了更轻松地调整大小测试的视觉效果,请尝试以下jQuery增强型JavaScript:(请参阅解释说明,如果您愿意,请删除评论)

  //这个第一行和JavaScript的`document.ready = function(){} 
//相同一旦文档被加载并准备好去
//在< head>中使用它是安全的。或者在< body>并会始终确保您的JS运行的页面加载
$(function(){
//这里我使用.on而不是直接refence到事件,因为这只是jQuery
//你以后会学习你可以使用这种预编写方法来打开/关闭与特定事件签署的方法
$(window).on('resize',function(e){
//小JS提示,不需要写`var`五万次,只需用一个逗号并写下你的新变量
var x = $(this).width(),//指定窗口宽度的变量到`x`
y = $(this).height(),//窗口高度的变量赋值为`y`
z = x / y,//您在代码中使用的转换在你的问题中,有很多不同的方式来测试尺寸变化,做一些谷歌搜索宽高比,因为它通常是最好的方式去
//下一行有点复杂
//它是确定一个变量基于'inline if语句'的结果
//它说什么:if(id为'myOutput'的元素存在)然后指定该元素并清空它的所有HTML,否则使用jQuery的元素对象构建元素方法并将其附加到< body>
// jQuery的元素对象的构建就是ez,只要记住它就像这样:jQuery(< tagName />,{object of attributes})
output = $('#myOutput')。长度 ? $('#myOutput')。empty():$('< div />',{id:'myOutput',style:'background:#ffa; padding:10px; position:fixed; right:30px; appendTo('body'),
//下面几行构建内部HTML,用于显示我们的窗口deminsions的结果
pX = $( '< p />',{text:'x:'+ x})。appendTo(output),
pY = $('< p />',{text:'y:' + y})。appendTo(output),
pZ = $('< p />',{text:'z:'+ z.toFixed(5)})。
});
))

如果您现在使用Google Chrome,那么您可以测试马上!只需按 F12 并点击控制台标签。复制下面的最小化代码,然后单击控制台。你应该看到一个闪烁的光标准备好输入。粘贴代码并按回车!然后调整窗口大小并观看右上角! * 笔记 在最右上角,您可能会看到Chrome自己的大小框。我的背景为黄色

缩小代码:

  $(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:# appendTo(body); $(< p />,{text:};} appendTo(b); $(< p />,{text:y:+ c})。appendTo(b); $(< p / ,{text:z:+ d.toFixed(5)})。appendTo(b)})}); 


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

解决方案

After reading your question and comments, 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. Welcome to awesomsauce!

Now as to an easier visual for resize testing, try the following jQuery enhanced JavaScript: (commented for explanations, remove comments 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 refence 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 comma 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 complicated
            //  It's assining 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 ez, 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 deminsions
            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)})});

这篇关于如何动态检测浏览器视口大小的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆