CSS奇技淫巧之VIEWPORT

CSS奇技淫巧之VIEWPORT:https://www.jianshu.com/p/96af79d121cc

假设有一个网页,有一个宽度为10%的sidebar,我们不断的拉伸浏览器,sidebar的宽度也在不断的增加,反之减少。在手机上看网页的时候,我们不断的滚动网页或者拉伸网页来改变内容呈现。这些机制是怎样实现的呢?是否是浏览器在不断的重绘节点(reflow, repaint)来做不同的展示呢?

当然不是!浏览器实现这一套机制的原理是viewport(视口)。我们在你不知道的CSS——BFC(块级格式化上下文)中介绍了BFC,而html节点则是最顶级的BFC,viewport则是用来约束html显示的区域。事实上,viewport又可分为visual viewport和layout viewport。为了了解这两个viewport的区别,我们不妨看看stackoverflow上的解释

The visual viewport is the part of the page that’s currently shown on-screen.
The layout viewport can be considerably wider than the visual viewport, and contains elements that appear and do not appear on the screen.
Imagine the layout viewport as being a large image which does not change size or shape. Now imagine you have a smaller frame through which you look at the large image. The small frame is surrounded by opaque material which obscures your view of all but a portion of the large image. The portion of the large image that you can see through the frame is the visual viewport. You can back away from the large image while holding your frame (zoom out) to see the entire image at once, or you can move closer (zoom in) to see only a portion. You can also change the orientation of the frame, but the size and shape of the large image (layout viewport) never changes.

也就是说,visual viewport是页面显示到屏幕上的可见区域,而layout viewport则是一个比较比visual viewport大的区域。我们可以假定是通过一个相框在看一个无限大的区域,只有其中的一部分能看到,其他部分被相框周边遮挡了。我们通过移动相框位置或者离这个区域的距离,能看到不同的内容或者放缩内容的大小,而在整个过程中,该区域的内容并未发生任何变化。这个比喻形象的模拟和解释了我们拖动滚动条以及对页面放缩的过程,整个过程中并未触发页面的layout,只是可视区域发生变化而已!

事实上,设备对自身的layout viewport也有其默认设定:

 
default layout viewport size

由此,我们不难理解,在移动端开发时,我们需要在网页中加入viewport设置:

<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">

这里将layout viewport的宽度设置成设备像素宽度,事实上这里只设置initial-scale=1也相当于将layout viewport设置和visual viewport大小相同。

另外,值得注意的一点是,window.innerWidth/Height获取的是layout viewport的宽度,而document.documentElement.clientWidth/Height获取到的是visual viewport的宽度,相差的是滚动条的宽度。未设置viewport,这二者将返回默认layout viewport宽度。

此外,关于事件绑定中的几个位置,clientX/Y相对于visual viewport, pageX/Y相对于页面,screenX/Y相对于屏幕,在有滚动条的情况下,我们最常用的应该是pageX/Y了。

参考文章
stackflow-viewport
两个viewport的故事(第一部分)
两个viewport的故(第二部分)
深入了解viewport和px
移动前端开发之viewport的深入理解



作者:小胖子嘿嘿嘿
链接:https://www.jianshu.com/p/96af79d121cc
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

posted on 2020-02-18 21:17  byd张小伟  阅读(215)  评论(0编辑  收藏  举报