Skip to content

Instantly share code, notes, and snippets.

@ambar
Created February 2, 2012 06:30
Show Gist options
  • Save ambar/1721991 to your computer and use it in GitHub Desktop.
Save ambar/1721991 to your computer and use it in GitHub Desktop.
chrome 中页面缩放时保持布局
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Page Zoom Test</title>
<style type="text/css">
body{
font:20px/1.5 Cambria,Georgia,serif;
}
.fixed{
font-size:10px;
line-height:3;
background:#9c2;
position: fixed;
right:10px;bottom:10px;width:300px;height:300px;
border:5px solid #07a;
}
.text-size-adjust{
-webkit-text-size-adjust:none;
right:1em;bottom:1em;width:30em;height:30em;
border-width:.5em!important;
}
@media only screen and (min-device-width : 320px) {
.fixed {}
}
</style>
</head>
<body>
<h1>-webkit-text-size-adjust</h1>
<form>
<label><input type="radio" name="adjust" value="js" checked>js</label>
<label><input type="radio" name="adjust" value="css">css</label>
</form>
<div id="fixed" class="fixed">
<p>line</p>
<p>line</p>
<p>line</p>
<p>line</p>
</div>
<pre id="log"></pre>
<script>
$ = document.querySelector.bind(document)
log = $('#log')
fixed = $('#fixed')
cls = 'text-size-adjust'
var resize = function(e) {
var ratio = window.outerWidth / window.innerWidth
log.textContent = [window.outerWidth, window.innerWidth, ratio].join('\t')
fixed.style.zoom = 1 / ratio
}
var adjust = function() {
window.onresize = resize
resize()
}
adjust()
$('form').onchange = function(e) {
if( e.target.value === 'js' ){
fixed.classList.remove(cls)
adjust()
}else{
fixed.style.zoom = ''
window.onresize = null
fixed.classList.add(cls)
}
}
</script>
</body>
</html>
@ambar
Copy link
Author

ambar commented Feb 2, 2012

chrome 中最有效的是使用 CSS ,并且使用相对单位
JavaScript 操纵 zoom 样式会导致闪烁

为什么用了 window.outerWidth ? 不变量。
新版 chrome 中,已经获取不到 document.width : https://bugs.webkit.org/show_bug.cgi?id=72591

browser pixels -> CSS pixels system pixels -> device pixels
http://www.quirksmode.org/m/widths.html

CSS Values and Units Reference
http://msdn.microsoft.com/en-us/library/ie/ms531211(v=vs.85).aspx

When should you use em over pixels in CSS?
www.quora.com/When-should-you-use-em-over-pixels-in-CSS

FONT SIZING WITH REM
http://snook.ca/archives/html_and_css/font-size-with-rem

http://stackoverflow.com/questions/1713771/how-to-detect-page-zoom-level-in-all-modern-browsers

@ambar
Copy link
Author

ambar commented Feb 3, 2012

背景图片可能需要:

background-size: contain

https://developer.mozilla.org/en/CSS/background-size

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment