javascript 如何动态检测浏览器视口大小的变化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28699255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dynamically detect browser viewport change in size?
提问by pearlescentcrescent
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
这是 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";
}) ;
});
What part is dynamic?
什么部分是动态的?
This console.log, I haven't used that before
这个console.log,我没用过
Any help would be greatly appreciatedd
任何帮助将不胜感激
回答by SpYk3HH
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:
首先,学习使用Chrome 的开发工具。他们太棒了!你现在需要知道的最重要的事情是:
To use console.log
:
使用console.log
:
- In your JavaScript, write a line like
console.log('Hello World!');
- Open that page in Google Chrome
- Press F12To Toggle (Open/Close) the DevTools
- 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. - Click on the tab labeled
Console
- Viola! You should see
Hello World!
if that line of JS has run. - Welcome to awesomsauce!
- 在你的 JavaScript 中,写一行像
console.log('Hello World!');
- 在Google Chrome 中打开该页面
- 按下F12以切换(打开/关闭)DevTools
- 它可能会在
Resources
选项卡上,这是检查所有资源是否已加载的好地方,但不是您要查找的资源。 - 单击标记的选项卡
Console
- 中提琴!您应该查看
Hello World!
该行 JS 是否已运行。 - 欢迎来到真棒酱!
Now as to an easier visual for resize testing, try the following jQuery enhanced JavaScript: (commented for explanations, remove comments if you please)
现在为了调整大小测试的更简单的视觉效果,请尝试以下 jQuery 增强型 JavaScript:(注释以获取解释,如果您愿意,请删除注释)
// 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 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 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! *note
in upper most right you will probably see Chrome's own size box. Mine has a yellow background
如果您现在正在使用 Google Chrome,那么您可以立即进行测试!只需按下F12
并单击Console
选项卡。复制下面最小化的代码,然后单击Console
. 您应该会看到一个闪烁的光标可供输入。粘贴代码并按回车键!然后只需调整窗口大小并观看右上角!*note
在右上角,您可能会看到 Chrome 自己的尺寸框。我的是黄色背景
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)})});