简体   繁体   English

窗口宽度-CSS vs JavaScript

[英]window width - css vs javascript

<link rel="stylesheet" href='media700.css' media="screen and (max-width:700px)">

JS JS

var a = window.outerWidth;
console.log(a); // 711

According the javascript calculation at the moment of switching stylesheet media700 is used on 711px and not 700px window width. 根据切换样式表时的javascript计算, media700用于711px而不是700px窗口宽度。

Assuming your question is "Why?", since you just made statements above: 假设您的问题是“为什么?”,因为您刚才在上面说过:

From MDN : MDN

Window.outerWidth gets the width of the outside of the browser window. Window.outerWidth获取浏览器窗口外部的宽度。 It represents the width of the whole browser window including sidebar (if expanded), window chrome and window resizing borders/handles. 它代表整个浏览器窗口的宽度,包括侧栏(如果已展开),窗口镶边和窗口调整大小的边框/句柄。

Also from MDN : 同样来自MDN

The width media feature describes the width of the rendering surface of the output device (such as the width of the document window , or the width of the page box on a printer). 宽度介质功能描述了输出设备的渲染表面宽度 (例如文档窗口的宽度或打印机上的页面框的宽度)。

The 11px difference is the window frame, scrollbar, etc. 11px的区别是窗口框架,滚动条等。

Just use innerWidth instead and you will see they share the same value. 只需使用innerWidth代替,您将看到它们共享相同的值。

As soon as you reach 700px and lower you will see the text 700px using a css media query and a background change with js. 一旦达到700px或更低,您将看到使用CSS媒体查询和js进行背景更改的文本700px。

Resize the demo in full page view. 在全页面视图中调整演示的大小。


jsfiddle jsfiddle


 $(window).on("resize", function() { var innderWidth = $(this).innerWidth(); $("span").text(innderWidth + "px"); if (innderWidth <= 700) { $("body").css("background-color", "gold"); } else { $("body").css("background-color", ""); } }); 
 body { margin: 0; } p { margin: 0; background-color: dodgerblue; font-size: 3em; } @media (max-width: 700px) { body::after { font-size: 10em; content: "700px"; } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> Window inner width: <span></span> </p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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