手機端奇葩彙總

原文:https://github.com/zhongDZ/zhongdz.github.com/issues/37

 

這裏收集了許多移動端上遇到的各種坑與相對解決方案

##工具類網站

HTML5 與 CSS3 技術應用評估

各種奇妙的hack

幾乎所有設備的屏幕尺寸與像素密度表

移動設備參數表

ios端移動設備參數速查

瀏覽器兼容表

移動設備查詢器

移動設備適配庫

移動設備適配庫2

viewport與設備尺寸在線檢測器

html5 移動端兼容性速查

在線轉換字體

css3 選擇器測試

兼容性速查表

瀏覽器的一些獨特參數

各種各樣的媒體查詢收集

css3 動畫在線製作器

css3 漸變在線製作器

移動端手勢表

webkit獨有的樣式分析

HTML5 Cross Browser Polyfills

HTML5 POLYFILLS

##iphone6的那些事

iPhone 6 屏幕揭祕

##響應式測試工具

Firefox 瀏覽器內置了 自定義設計視圖 的功能,可以通過 Firefox->Web 開發者->自定義設計視圖(或者摁下 Shift + Ctrl + m )。相比網絡工具,運行更加流暢,無需聯網。

判斷 iPad 和 iPhone 的版本和狀態的 CSS 媒體查詢代碼

Viewport Resizer

http://beta.screenqueri.es/

http://responsivepx.com

http://www.responsinator.com/

http://resizemybrowser.com/

https://quirktools.com/screenfly/

媒體查詢常用樣式表:

	<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">    // 豎放加載
	<link rel="stylesheet" media="all and (orientation:landscape)"href="landscape.css">   // 橫放加載
豎屏時使用的樣式
	<style media="all and (orientation:portrait)" type="text/css">
		#landscape { display: none; }
	</style>
//橫屏時使用的樣式
	<style media="all and (orientation:landscape)" type="text/css">
		#portrait { display: none; }
	</style>

##Web app 開發的最佳實踐與中文總結

It’s not a web app. It’s an app you install from the web.

當前 WEB APP 開發的最佳實踐

如何自適應網頁屏幕
以及配套的解決方案

##來自maxzhang的一些移動端經驗總結乾貨

移動Web單頁應用開發實踐——頁面結構化

移動Web產品前端開發口訣——“快”

移動Web開發,4行代碼檢測瀏覽器是否支持position:fixed

使用border-image實現類似iOS7的1px底邊

移動端web頁面使用position:fixed問題總結

移動Web開發實踐——解決position:fixed自適應BUG

移動手機瀏覽器m3u8格式視頻流播放支持程度測試

##本資料很多引用了指尖上的js系列

指尖下的js ——多觸式web前端開發之一:對於Touch的處理

指尖下的js ——多觸式web前端開發之二:處理簡單手勢

指尖下的js —— 多觸式web前端開發之三:處理複雜手勢

##基礎知識

###meta標籤

meta標籤大全 http://segmentfault.com/blog/ciaocc/1190000002407912

meta標籤,這些meta標籤在開發webapp時起到非常重要的作用

	<meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0" name="viewport" />
	<meta content="yes" name="apple-mobile-web-app-capable" />
	<meta content="black" name="apple-mobile-web-app-status-bar-style" />
	<meta content="telephone=no" name="format-detection" />

第一個meta標籤表示:強制讓文檔的寬度與設備的寬度保持1:1,並且文檔最大的寬度比例是1.0,且不允許用戶點擊屏幕放大瀏覽;
尤其要注意的是content裏多個屬性的設置一定要用分號+空格來隔開,如果不規範將不會起作用。

注意根據 public_00 提供的資料補充,content 使用分號作爲分隔,在老的瀏覽器是支持的,但不是規範寫法。

規範的寫法應該是使用逗號分隔,參考 Safari HTML Reference - Supported Meta Tags 和 Android - Supporting Different Screens in Web Apps

其中:

  • width - viewport的寬度
  • height - viewport的高度
  • initial-scale - 初始的縮放比例
  • minimum-scale - 允許用戶縮放到的最小比例
  • maximum-scale - 允許用戶縮放到的最大比例
  • user-scalable - 用戶是否可以手動縮放

第二個meta標籤是iphone設備中的safari私有meta標籤,它表示:允許全屏模式瀏覽;
第三個meta標籤也是iphone的私有標籤,它指定的iphone中safari頂端的狀態條的樣式;
第四個meta標籤表示:告訴設備忽略將頁面中的數字識別爲電話號碼

在設置了initial-scale=1 之後,我們終於可以以1:1 的比例進行頁面設計了。
關於viewport,還有一個很重要的概念是:iphone 的safari 瀏覽器完全沒有滾動條,而且不是簡單的“隱藏滾動條”,
是根本沒有這個功能。iphone 的safari 瀏覽器實際上從一開始就完整顯示了這個網頁,然後用viewport 查看其中的一部分。
當你用手指拖動時,其實拖的不是頁面,而是viewport。瀏覽器行爲的改變不止是滾動條,交互事件也跟普通桌面不一樣。
(請參考:指尖的下JS 系列文章)

更詳細的 viewport 相關的知識也可以參考

此像素非彼像素

##移動開發事件

手機瀏覽器常用手勢動作監聽封裝

###手勢事件

  • touchstart //當手指接觸屏幕時觸發
  • touchmove //當已經接觸屏幕的手指開始移動後觸發
  • touchend //當手指離開屏幕時觸發
  • touchcancel

###觸摸事件

  • gesturestart //當兩個手指接觸屏幕時觸發
  • gesturechange //當兩個手指接觸屏幕後開始移動時觸發
  • gestureend

###屏幕旋轉事件

  • onorientationchange

###檢測觸摸屏幕的手指何時改變方向

  • orientationchange

###touch事件支持的相關屬性

  • touches
  • targetTouches
  • changedTouches
  • clientX    // X coordinate of touch relative to the viewport (excludes scroll offset)
  • clientY    // Y coordinate of touch relative to the viewport (excludes scroll offset)
  • screenX    // Relative to the screen
  • screenY    // Relative to the screen
  • pageX     // Relative to the full page (includes scrolling)
  • pageY     // Relative to the full page (includes scrolling)
  • target     // Node the touch event originated from
  • identifier   // An identifying number, unique to each touch event
  • 屏幕旋轉事件:onorientationchange

###判斷屏幕是否旋轉

	function orientationChange() {
		switch(window.orientation) {
		  case 0:
				alert("肖像模式 0,screen-width: " + screen.width + "; screen-height:" + screen.height);
				break;
		  case -90:
				alert("左旋 -90,screen-width: " + screen.width + "; screen-height:" + screen.height);
				break;
		  case 90:
				alert("右旋 90,screen-width: " + screen.width + "; screen-height:" + screen.height);
				break;
		  case 180:
			  alert("風景模式 180,screen-width: " + screen.width + "; screen-height:" + screen.height);
			  break;
		};};

	addEventListener('load', function(){
		orientationChange();
		window.onorientationchange = orientationChange;
	});

###JS 單擊延遲
click 事件因爲要等待單擊確認,會有 300ms 的延遲,體驗並不是很好。

開發者大多數會使用封裝的 tap 事件來代替click 事件,所謂的 tap 事件由 touchstart 事件 + touchmove 判斷 + touchend 事件封裝組成。

Creating Fast Buttons for Mobile Web Applications

Eliminate 300ms delay on click events in mobile Safari

##WebKit CSS:
攜程 UED 整理的 Webkit CSS 文檔 ,全面、方便查詢,下面爲常用屬性。

①“盒模型”的具體描述性質的包圍盒塊內容,包括邊界,填充等等。

	-webkit-border-bottom-left-radius: radius;
	-webkit-border-top-left-radius: horizontal_radius vertical_radius;
	-webkit-border-radius: radius;      //容器圓角
	-webkit-box-sizing: sizing_model; 邊框常量值:border-box/content-box
	-webkit-box-shadow: hoff voff blur color; /*容器陰影(參數分別爲:水平X 方向偏移量;垂直Y方向偏移量;高斯模糊半徑值;陰影顏色值)*/
	-webkit-margin-bottom-collapse: collapse_behavior; /*常量值:collapse/discard/separate*/
	-webkit-margin-start: width;
	-webkit-padding-start: width;
	-webkit-border-image: url(borderimg.gif) 25 25 25 25 round/stretch round/stretch;
	-webkit-appearance: push-button;   /*內置的CSS 表現,暫時只支持push-button*/

②“視覺格式化模型”描述性質,確定了位置和大小的塊元素。

direction: rtl
unicode-bidi: bidi-override; 常量:bidi-override/embed/normal

③“視覺效果”描述屬性,調整的視覺效果塊內容,包括溢出行爲,調整行爲,能見度,動畫,變換,和過渡。

clip: rect(10px, 5px, 10px, 5px)
resize: auto; 常量:auto/both/horizontal/none/vertical
visibility: visible; 常量: collapse/hidden/visible
-webkit-transition: opacity 1s linear; 動畫效果 ease/linear/ease-in/ease-out/ease-in-out
-webkit-backface-visibility: visibler; 常量:visible(默認值)/hidden
-webkit-box-reflect: right 1px; 鏡向反轉
-webkit-box-reflect: below 4px -webkit-gradient(linear, left top, left bottom,
from(transparent), color-stop(0.5, transparent), to(white));
-webkit-mask-image: -webkit-gradient(linear, left top, left bottom, from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));;   //CSS 遮罩/蒙板效果
-webkit-mask-attachment: fixed; 常量:fixed/scroll
-webkit-perspective: value; 常量:none(默認)
-webkit-perspective-origin: left top;
-webkit-transform: rotate(5deg);
-webkit-transform-style: preserve-3d; 常量:flat/preserve-3d; (2D 與3D)

④“生成的內容,自動編號,並列出”描述屬性,允許您更改內容的一個組成部分,創建自動編號的章節和標題,和操縱的風格清單的內容。

content: “Item” counter(section) ” “;
This resets the counter.
First section
>two section
three section
counter-increment: section 1;
counter-reset: section;

⑤“分頁媒體”描述性能與外觀的屬性,控制印刷版本的網頁,如分頁符的行爲。

page-break-after: auto; 常量:always/auto/avoid/left/right
page-break-before: auto; 常量:always/auto/avoid/left/right
page-break-inside: auto; 常量:auto/avoid

⑥“顏色和背景”描述屬性控制背景下的塊級元素和顏色的文本內容的組成部分。

-webkit-background-clip: content; 常量:border/content/padding/text
-webkit-background-origin: padding; 常量:border/content/padding/text
-webkit-background-size: 55px; 常量:length/length_x/length_y

⑦ “字型”的具體描述性質的文字字體的選擇範圍內的一個因素。報告還描述屬性用於下載字體定義。

unicode-range: U+00-FF, U+980-9FF;

⑧“文本”描述屬性的特定文字樣式,間距和自動滾屏。

text-shadow: #00FFFC 10px 10px 5px;
text-transform: capitalize; 常量:capitalize/lowercase/none/uppercase
word-wrap: break-word; 常量:break-word/normal
-webkit-marquee: right large infinite normal 10s; 常量:direction(方向) increment(迭代次數) repetition(重複) style(樣式) speed(速度);
-webkit-marquee-direction: ahead/auto/backwards/down/forwards/left/reverse/right/up
-webkit-marquee-incrementt: 1-n/infinite(無窮次)
-webkit-marquee-speed: fast/normal/slow
-webkit-marquee-style: alternate/none/scroll/slide
-webkit-text-fill-color: #ff6600; 常量:capitalize, lowercase, none, uppercase
-webkit-text-security: circle; 常量:circle/disc/none/square
-webkit-text-size-adjust: none; 常量:auto/none;
-webkit-text-stroke: 15px #fff;
-webkit-line-break: after-white-space; 常量:normal/after-white-space
-webkit-appearance: caps-lock-indicator;
-webkit-nbsp-mode: space; 常量: normal/space
-webkit-rtl-ordering: logical; 常量:visual/logical
-webkit-user-drag: element; 常量:element/auto/none
-webkit-user-modify: read- only; 常量:read-write-plaintext-only/read-write/read-only
-webkit-user-select: text; 常量:text/auto/none

⑨“表格”描述的佈局和設計性能表的具體內容。

-webkit-border-horizontal-spacing: 2px;
-webkit-border-vertical-spacing: 2px;
-webkit-column-break-after: right; 常量:always/auto/avoid/left/right
-webkit-column-break-before: right; 常量:always/auto/avoid/left/right
–webkit-column-break-inside: logical; 常量:avoid/auto
-webkit-column-count: 3; //分欄
-webkit-column-rule: 1px solid #fff;
style:dashed,dotted,double,groove,hidden,inset,none,outset,ridge,solid

⑩“用戶界面”描述屬性,涉及到用戶界面元素在瀏覽器中,如滾動文字區,滾動條,等等。報告還描述屬性,範圍以外的網頁內容,如光標的標註樣式和顯示當您按住觸摸觸摸
目標,如在iPhone上的鏈接。

-webkit-box-align: baseline,center,end,start,stretch 常量:baseline/center/end/start/stretch
-webkit-box-direction: normal;常量:normal/reverse
-webkit-box-flex: flex_valuet
-webkit-box-flex-group: group_number
-webkit-box-lines: multiple; 常量:multiple/single
-webkit-box-ordinal-group: group_number
-webkit-box-orient: block-axis; 常量:block-axis/horizontal/inline-axis/vertical/orientation
–webkit-box-pack: alignment; 常量:center/end/justify/start

動畫過渡
這是 Webkit 中最具創新力的特性:使用過渡函數定義動畫。

-webkit-animation: title infinite ease-in-out 3s;
animation 有這幾個屬性:
-webkit-animation-name: //屬性名,就是我們定義的keyframes
-webkit-animation-duration:3s //持續時間
-webkit-animation-timing-function: //過渡類型:ease/ linear(線性) /ease-in(慢到快)/ease-out(快到慢) /ease-in-out(慢到快再到慢) /cubic-bezier
-webkit-animation-delay:10ms //動畫延遲(默認0)
-webkit-animation-iteration-count: //循環次數(默認1),infinite 爲無限
-webkit-animation-direction: //動畫方式:normal(默認 正向播放); alternate(交替方向,第偶數次正向播放,第奇數次反向播放)

這些同樣是可以簡寫的。但真正讓我覺的很爽的是keyframes,它能定義一個動畫的轉變過程供調用,過程爲0%到100%或from(0%)到to(100%)。簡單點說,只要你有想法,你想讓元素在這個過程中以什麼樣的方式改變都是很簡單的。

-webkit-transform: 類型(縮放scale/旋轉rotate/傾斜skew/位移translate)
scale(num,num) 放大倍率。scaleX 和 scaleY(3),可以簡寫爲:scale(* , *)
rotate(*deg) 轉動角度。rotateX 和 rotateY,可以簡寫爲:rotate(* , *)
Skew(*deg) 傾斜角度。skewX 和skewY,可簡寫爲:skew(* , *)
translate(*,*) 座標移動。translateX 和translateY,可簡寫爲:translate(* , *)。

###頁面描述

<link rel="apple-touch-icon-precomposed" href="http://www.xxx.com/App_icon_114.png" />
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://www.xxx.com/App_icon_72.png" />
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://www.xxx.com/App_icon_114.png" />

這個屬性是當用戶把連接保存到手機桌面時使用的圖標,如果不設置,則會用網頁的截圖。有了這,就可以讓你的網頁像APP一樣存在手機裏了

<link rel="apple-touch-startup-image" href="/img/startup.png" />

這個是APP啓動畫面圖片,用途和上面的類似,如果不設置,啓動畫面就是白屏,圖片像素就是手機全屏的像素

<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

這個描述是表示打開的web app的最上面的時間、信號欄是黑色的,當然也可以設置其它參數,詳細參數說明請參照:Safari HTML Reference - Supported Meta Tags

<meta name="apple-touch-fullscreen" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />

##常見的 iPhone 和 Android 屏幕參數。

  • 設備 分辨率 設備像素比率
  • Android LDPI 320×240 0.75
  • Iphone 3 & Android MDPI 320×480 1
  • Android HDPI 480×800 1.5
  • Iphone 4 960×640 2.0

iPhone 4的一個 CSS 像素實際上表現爲一塊 2×2 的像素。所以圖片像是被放大2倍一樣,模糊不清晰。

解決辦法:

1、頁面引用

<link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio: 0.75)" href="ldpi.css" />
<link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio: 1.0)" href="mdpi.css" />
<link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio: 1.5)" href="hdpi.css" />
<link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio: 2.0)" href="retina.css" />

2、CSS文件裏

#header {
	background:url(mdpi/bg.png);
}

@media screen and (-webkit-device-pixel-ratio: 1.5) {
	/*CSS for high-density screens*/
	#header {
		background:url(hdpi/bg.png);
	}
}

##移動 Web 開發經驗技巧

###點擊與click事件

對於a標記的點擊導航,默認是在onclick事件中處理的。而移動客戶端對onclick的響應相比PC瀏覽器有着明顯的幾百毫秒延遲。

在移動瀏覽器中對觸摸事件的響應順序應當是:

ontouchstart -> ontouchmove -> ontouchend -> onclick

因此,如果確實要加快對點擊事件的響應,就應當綁定ontouchend事件。

使用click會出現綁定點擊區域閃一下的情況,解決:給該元素一個樣式如下

-webkit-tap-highlight-color: rgba(0,0,0,0);

如果不使用click,也不能簡單的用touchstart或touchend替代,需要用touchstart的模擬一個click事件,並且不能發生touchmove事件,或者用zepto中的tap(輕擊)事件。

body
{
	-webkit-overflow-scrolling: touch;
}

用iphone或ipad瀏覽很長的網頁滾動時的滑動效果很不錯吧?不過如果是一個div,然後設置 height:200px;overflow:auto;的話,可以滾動但是完全沒有那滑動效果,很鬱悶吧?

我看到很多網站爲了實現這一效果,用了第三方類庫,最常用的是iscroll(包括新浪手機頁,百度等)
我一開始也使用,不過自從用了-webkit-overflow-scrolling: touch;樣式後,就完全可以拋棄第三方類庫了,把它加在body{}區域,所有的overflow需要滾動的都可以生效了。

另外有一篇比較全的移動端點擊解決方案 http://www.zhihu.com/question/28979857

###鎖定 viewport

ontouchmove="event.preventDefault()" //鎖定viewport,任何屏幕操作不移動用戶界面(彈出鍵盤除外)。

###利用 Media Query監聽

Media Query 相信大部分人已經使用過了。其實 JavaScript可以配合 Media Query這麼用:

var mql = window.matchMedia("(orientation: portrait)");
mql.addListener(handleOrientationChange);
handleOrientationChange(mql); 
function handleOrientationChange(mql) {
  if (mql.matches) {
    alert('The device is currently in portrait orientation ')
  } else {
    alert('The device is currently in landscape orientation')
  }}

藉助了 Media Query 接口做的事件監聽,所以很強大!

也可以通過獲取 CSS 值來使用 Media Query 判斷設備情況,詳情請看:JavaScript 依據 CSS Media Queries 判斷設備的方法

###rem最佳實踐

rem是非常好用的一個屬性,可以根據html來設定基準值,而且兼容性也很不錯。不過有的時候還是需要對一些莫名其妙的瀏覽器優雅降級。以下是兩個實踐

  1. http://jsbin.com/vaqexuge/4/edit 這有個demo,發現chrome當font-size小於12時,rem會按照12來計算。因此設置基準值要考慮這一點

  2. 可以用以下的代碼片段保證在低端瀏覽器下也不會出問題

    html { font-size: 62.5%; }
    body { font-size: 14px; font-size: 1.4rem; } /* =14px /
    h1 { font-size: 24px; font-size: 2.4rem; } /
     =24px */

###被點擊元素的外觀變化,可以使用樣式來設定:

-webkit-tap-highlight-color: 顏色

###檢測判斷 iPhone/iPod
開發特定設備的移動網站,首先要做的就是設備偵測了。下面是使用Javascript偵測iPhone/iPod的UA,然後轉向到專屬的URL。

if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
  if (document.cookie.indexOf("iphone_redirect=false") == -1) {
    window.location = "http://m.example.com";
  }
}

雖然Javascript是可以在水果設備上運行的,但是用戶還是可以禁用。它也會造成客戶端刷新和額外的數據傳輸,所以下面是服務器端偵測和轉向:

if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'],'iPod')) {
  header('Location: http://yoursite.com/iphone');
  exit();
}

###阻止旋轉屏幕時自動調整字體大小

html, body, form, fieldset, p, div, h1, h2, h3, h4, h5, h6 {-webkit-text-size-adjust:none;}

###模擬:hover僞類
因爲iPhone並沒有鼠標指針,所以沒有hover事件。那麼CSS :hover僞類就沒用了。但是iPhone有Touch事件,onTouchStart 類似 onMouseOver,onTouchEnd 類似 onMouseOut。所以我們可以用它來模擬hover。使用Javascript:

var myLinks = document.getElementsByTagName('a');
for(var i = 0; i < myLinks.length; i++){
  myLinks[i].addEventListener(’touchstart’, function(){this.className = “hover”;}, false);
  myLinks[i].addEventListener(’touchend’, function(){this.className = “”;}, false);
}

然後用CSS增加hover效果:

a:hover, a.hover { /* 你的hover效果 */ }

這樣設計一個鏈接,感覺可以更像按鈕。並且,這個模擬可以用在任何元素上。

###Flexbox 佈局

Flex 模板和實例

深入瞭解 Flexbox 伸縮盒模型

CSS Flexbox Intro

http://www.w3.org/TR/css3-flexbox/

###居中問題

居中是移動端跟pc端共同的噩夢。這裏有兩種兼容性比較好的新方案。

  • table佈局法

    .box{
    text-align:center;
    display:table-cell;
    vertical-align:middle;
    }

  • 老版本flex佈局法

    .box{
    display:-webkit-box;
    -webkit-box-pack: center;
    -webkit-box-align: center;
    text-align:center;
    }

以上兩種其實分別是retchat跟ionic的佈局基石。

這裏有更詳細的更多的選擇http://www.zhouwenbin.com/%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%AD%E7%9A%84%E5%87%A0%E7%A7%8D%E6%96%B9%E6%B3%95/ 來自周文彬的博客

###移動端實現標題文字截斷
http://www.75team.com/archives/611

###處理 Retina 雙倍屏幕

(經典)Using CSS Sprites to optimize your website for Retina Displays

使用CSS3的background-size優化蘋果的Retina屏幕的圖像顯示

使用 CSS sprites 來優化你的網站在 Retina 屏幕下顯示

(案例)CSS IMAGE SPRITES FOR RETINA (HIRES) DEVICES

###input類型爲date情況下不支持placeholder(來自於江水)

這其實是瀏覽器自己的處理。因爲瀏覽器會針對此類型 input 增加 datepicker 模塊。

對 input type date 使用 placeholder 的目的是爲了讓用戶更準確的輸入日期格式,iOS 上會有 datepicker 不會顯示 placeholder 文字,但是爲了統一表單外觀,往往需要顯示。Android 部分機型沒有 datepicker 也不會顯示 placeholder 文字。

桌面端(Mac)

  • Safari 不支持 datepicker,placeholder 正常顯示。
  • Firefox 不支持 datepicker,placeholder 正常顯示。
  • Chrome 支持 datepicker,顯示 年、月、日 格式,忽略 placeholder。

移動端

  • iPhone5 iOS7 有 datepicker 功能,但是不顯示 placeholder。
  • Andorid 4.0.4 無 datepicker 功能,不顯示 placeholder

解決方法:

<input placeholder="Date" class="textbox-n" type="text" onfocus="(this.type='date')"  id="date"> 

因爲text是支持placeholder的。因此當用戶focus的時候自動把type類型改變爲date,這樣既有placeholder也有datepicker了

###判斷照片的橫豎排列

有這樣一種需求,需要判斷用戶照片是橫着拍出來的還是豎着拍出來的,這裏需要使用照片得exif信息:

$("input").change(function() {
    var file = this.files[0];
    fr   = new FileReader;

    fr.onloadend = function() {
        var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));
        alert(exif.Orientation);
    };

    fr.readAsBinaryString(file);
});

可以使用這兩個庫 來取exif信息http://www.nihilogic.dk/labs/binaryajax/binaryajax.js http://www.nihilogic.dk/labs/exif/exif.js

###Android上當viewport的width大於device-width時出現文字無故折行的解決辦法

http://www.iunbug.com/archives/2013/04/23/798.html

###白屏解決與優化方案

當前很多無線頁面都使用前端模板進行數據渲染,那麼在糟糕的網速情況下,一進去頁面,看到的不是白屏就是 loading,這成爲白屏問題。

此問題發生的原因基本可以歸結爲網速跟靜態資源

1、css文件加載需要一些時間,在加載的過程中頁面是空白的。 解決:可以考慮將css代碼前置和內聯。
2、首屏無實際的數據內容,等待異步加載數據再渲染頁面導致白屏。 解決:在首屏直接同步渲染html,後續的滾屏等再採用異步請求數據和渲染html。
3、首屏內聯js的執行會阻塞頁面的渲染。 解決:儘量不在首屏html代碼中放置內聯腳本。(來自翔歌)

解決方案

根本原因是客戶端渲染的無力,因此最簡單的方法是在服務器端,使用模板引擎渲染所有頁面。同時

1減少文件加載體積,如html壓縮,js壓縮
2加快js執行速度 比如常見的無限滾動的頁面,可以使用js先渲染一個屏幕範圍內的東西
3提供一些友好的交互,比如提供一些假的滾動條
4使用本地存儲處理靜態文件。

###如何實現打開已安裝的app,若未安裝則引導用戶安裝?

來自 http://gallery.kissyui.com/redirectToNative/1.2/guide/index.html kissy mobile
通過iframe src發送請求打開app自定義url scheme,如taobao://home(淘寶首頁) 、etao://scan(一淘掃描));
如果安裝了客戶端則會直接喚起,直接喚起後,之前瀏覽器窗口(或者掃碼工具的webview)推入後臺;
如果在指定的時間內客戶端沒有被喚起,則js重定向到app下載地址。
大概實現代碼如下

goToNative:function(){

	if(!body) {
            setTimeout(function(){
                doc.body.appendChild(iframe);
            }, 0);
        } else {
            body.appendChild(iframe);
        }

setTimeout(function() {
            doc.body.removeChild(iframe);
            gotoDownload(startTime);//去下載,下載鏈接一般是itunes app store或者apk文件鏈接
            /**
             * 測試時間設置小於800ms時,在android下的UC瀏覽器會打開native app時並下載apk,
             * 測試android+UC下打開native的時間最好大於800ms;
             */
        }, 800);
}

需要注意的是 如果是android chrome 25版本以後,在iframe src不會發送請求,
原因如下https://developers.google.com/chrome/mobile/docs/intents ,通過location href使用intent機制拉起客戶端可行並且當前頁面不跳轉。

window.location = 'intent://' + schemeUrl + '#Intent;scheme=' + scheme + ';package=' + self.package + ';end';

補充一個來自三水清的詳細講解 http://js8.in/2013/12/16/ios%E4%BD%BF%E7%94%A8schema%E5%8D%8F%E8%AE%AE%E8%B0%83%E8%B5%B7app/

###active的兼容(來自薛端陽)

今天發現,要讓a鏈接的CSS active僞類生效,只需要給這個a鏈接的touch系列的任意事件touchstart/touchend綁定一個空的匿名方法即可hack成功

<style>
a {
color: #000;
}
a:active {
color: #fff;
}
</style>
<a herf=”asdasd”>asdasd</a>
<script>
var a=document.getElementsByTagName(‘a’);
for(var i=0;i<a.length;i++){
a[i].addEventListener(‘touchstart’,function(){},false);
}
</script>

###消除transition閃屏

兩個方法:使用css3動畫的時儘量利用3D加速,從而使得動畫變得流暢。動畫過程中的動畫閃白可以通過 backface-visibility 隱藏。

-webkit-transform-style: preserve-3d;
/*設置內嵌的元素在 3D 空間如何呈現:保留 3D*/
-webkit-backface-visibility: hidden;
/*(設置進行轉換的元素的背面在面對用戶時是否可見:隱藏)*/

###測試是否支持svg圖片

document.implementation.hasFeature("http:// www.w3.org/TR/SVG11/feature#Image", "1.1")

##考慮兼容“隱私模式”(from http://blog.youyo.name/archives/smarty-phones-webapp-deverlop-advance.html)
ios的safari提供一種“隱私模式”,如果你的webapp考慮兼容這個模式,那麼在使用html5的本地存儲的一種————localStorage時,可能因爲“隱私模式”下沒有權限讀寫localstorge而使代碼拋出錯誤,導致後續的js代碼都無法運行了。

既然在safari的“隱私模式”下,沒有調用localStorage的權限,首先想到的是先判斷是否支持localStorage,代碼如下:

if('localStorage' in window){
    //需要使用localStorage的代碼寫在這
}else{
    //不支持的提示和向下兼容代碼
}

測試發現,即使在safari的“隱私模式”下,’localStorage’ in window的返回值依然爲true,也就是說,if代碼塊內部的代碼依然會運行,問題沒有得到解決。
接下來只能相當使用try catch了,雖然這是一個不太推薦被使用的方法,使用try catch捕獲錯誤,使後續的js代碼可以繼續運行,代碼如下:

try{
    if('localStorage' in window){
         //需要使用localStorage的代碼寫在這
    }else{
         //不支持的提示和向下兼容代碼
    }
}catch(e){
    // 隱私模式相關提示代碼和不支持的提示和向下兼容代碼
}

所以,提醒大家注意,在需要兼容ios的safari的“隱私模式”的情況下,本地存儲相關的代碼需要使用try catch包裹並降級兼容。

###安卓手機點擊鎖定頁面效果問題

有些安卓手機,頁面點擊時會停止頁面的javascript,css3動畫等的執行,這個比較蛋疼。不過可以用阻止默認事件解決。詳細見
http://stackoverflow.com/questions/10246305/android-browser-touch-events-stop-display-being-updated-inc-canvas-elements-h

function touchHandlerDummy(e)
{
    e.preventDefault();
    return false;
}
document.addEventListener("touchstart", touchHandlerDummy, false);
document.addEventListener("touchmove", touchHandlerDummy, false);
document.addEventListener("touchend", touchHandlerDummy, false);

###消除ie10裏面的那個叉號
IE Pseudo-elements

input:-ms-clear{display:none;}

###關於ios與os端字體的優化(橫豎屏會出現字體加粗不一致等)
mac下網頁中文字體優化

UIWebView font is thinner in portrait than landscape

##判斷用戶是否是“將網頁添加到主屏後,再從主屏幕打開這個網頁”的

navigator.standalone

###隱藏地址欄 & 處理事件的時候,防止滾動條出現:

// 隱藏地址欄  & 處理事件的時候 ,防止滾動條出現
addEventListener('load', function(){
		setTimeout(function(){ window.scrollTo(0, 1); }, 100);
});

###ios7 可以通過meta標籤的minimal來隱藏地址欄了
http://darkblue.sdf.org/weblog/ios-7-dot-1-mobile-safari-minimal-ui.html

###判斷是否爲iPhone:

// 判斷是否爲 iPhone :
function isAppleMobile() {
	return (navigator.platform.indexOf('iPhone') != -1);
};

###localStorage:

var v = localStorage.getItem('n') ? localStorage.getItem('n') : "";   // 如果名稱是  n 的數據存在 ,則將其讀出 ,賦予變量  v  。
localStorage.setItem('n', v);                                           // 寫入名稱爲 n、值爲  v  的數據
localStorage.removeItem('n');        // 刪除名稱爲  n  的數據

###使用特殊鏈接:
如果你關閉自動識別後 ,又希望某些電話號碼能夠鏈接到 iPhone 的撥號功能 ,那麼可以通過這樣來聲明電話鏈接 ,

<a href="tel:12345654321">打電話給我</a>
<a href="sms:12345654321">發短信</a>

或用於單元格:

<td onclick="location.href='tel:122'">

###自動大寫與自動修正
要關閉這兩項功能,可以通過autocapitalize 與autocorrect 這兩個選項:

<input type="text" autocapitalize="off" autocorrect="off" />

###不讓 Android 識別郵箱

<meta content="email=no" name="format-detection" />

###禁止 iOS 彈出各種操作窗口

-webkit-touch-callout:none

###禁止用戶選中文字

-webkit-user-select:none

###動畫效果中,使用 translate 比使用定位性能高

Why Moving Elements With Translate() Is Better Than Pos:abs Top/left

###拿到滾動條

window.scrollY
window.scrollX

比如要綁定一個touchmove的事件,正常的情況下類似這樣(來自呼吸二氧化碳)

$('div').on('touchmove', function(){
//.….code
{});

而如果中間的code需要處理的東西多的話,fps就會下降影響程序順滑度,而如果改成這樣

$('div').on('touchmove', function(){
setTimeout(function(){
//.….code
},0);
{});

把代碼放在setTimeout中,會發現程序變快.

###關於 iOS 系統中,Web APP 啓動圖片在不同設備上的適應性設置

http://stackoverflow.com/questions/4687698/mulitple-apple-touch-startup-image-resolutions-for-ios-web-app-esp-for-ipad/10011893#10011893

###position:sticky與position:fixed佈局
http://www.zhouwenbin.com/positionsticky-%E7%B2%98%E6%80%A7%E5%B8%83%E5%B1%80/
http://www.zhouwenbin.com/sticky%E6%A8%A1%E6%8B%9F%E9%97%AE%E9%A2%98/

###關於 iOS 系統中,中文輸入法輸入英文時,字母之間可能會出現一個六分之一空格
可以通過正則去掉

this.value = this.value.replace(/\u2006/g, '');

###關於android webview中,input元素輸入時出現的怪異情況
見下圖

怪異圖

Android Web 視圖,至少在 HTC EVO 和三星的 Galaxy Nexus 中,文本輸入框在輸入時表現的就像佔位符。情況爲一個類似水印的東西在用戶輸入區域,一旦用戶開始輸入便會消失(見圖片)。

在 Android 的默認樣式下當輸入框獲得焦點後,若存在一個絕對定位或者 fixed 的元素,佈局會被破壞,其他元素與系統輸入字段會發生重疊(如搜索圖標將消失爲搜索字段),可以觀察到佈局與原始輸入字段有偏差(見截圖)。

這是一個相當複雜的問題,以下簡單佈局可以重現這個問題:

<label for="phone">Phone: *</label>
<input type="tel" name="phone" id="phone" minlength="10" maxlength="10" inputmode="latin digits" required="required" />

解決方法

-webkit-user-modify: read-write-plaintext-only

詳細參考http://www.bielousov.com/2012/android-label-text-appears-in-input-field-as-a-placeholder/
注意,該屬性會導致中文不能輸入詞組,只能單個字。感謝鬼哥與飛(遊勇飛)貢獻此問題與解決方案

另外,在position:fixed後的元素裏,儘量不要使用輸入框。更多的bug可參考
http://www.cosdiv.com/page/M0/S882/882353.html

依舊無法解決(摩托羅拉ME863手機),則使用input:text類型而非password類型,並設置其設置 -webkit-text-security: disc; 隱藏輸入密碼從而解決。

###JS動態生成的select下拉菜單在Android2.x版本的默認瀏覽器裏不起作用

解決方法刪除了overflow-x:hidden; 然後在JS生成下來菜單之後focus聚焦,這兩步操作之後解決了問題。(來自島都-小Qi)

參考http://stackoverflow.com/questions/4697908/html-select-control-disabled-in-android-webview-in-emulator

###Andriod 上去掉語音輸入按鈕

input::-webkit-input-speech-button {display: none}

##IE10 的特殊鼠標事件

IE10 事件監聽

##iOS 輸入框最佳實踐

Mobile-friendly input of a digits + spaces string (a credit card number)

HTML5 input type number vs tel

iPhone: numeric keyboard for text input

Text Programming Guide for iOS - Managing the Keyboard

HTML5 inputs and attribute support

##往返緩存問題

點擊瀏覽器的回退,有時候不會自動執行js,特別是在mobilesafari中。這與**往返緩存(bfcache)**有關係。有很多hack的處理方法,可以參考

http://stackoverflow.com/questions/24046/the-safari-back-button-problem

http://stackoverflow.com/questions/11979156/mobile-safari-back-button

##不暫停的計時器(safari的進程凍結)

https://www.imququ.com/post/ios-none-freeze-timer.html
或者可以用postmessage方式:
主頁面:

    // 解決ios safari tab在後臺會遭遇進程凍結問題
    // http://www.apple.com/safari/#gallery-icloud-tabs
    // Safari takes advantage of power-saving technologies such as App Nap, which puts background Safari tabs into a low-power state until you start using them again. In addition, Safari Power Saver conserves battery life by intelligently pausing web videos and other plug‑in content when they’re not front and center on the web pages you visit. All told, Safari on OS X Mavericks lets you browse up to an hour longer than with Chrome or Firefox.1
    var work;
    function startWorker() {
        if (typeof(Worker) !== "undefined") {
            if (typeof(work) == "undefined") {
                work = new Worker("/workers.js");
            }
            work.onmessage = function(event) {
                // document.getElementById("result-count").innerHTML = event.data.count;
                // document.getElementById("result-url").innerHTML = event.data.targetURL;
                if (target && event.data.targetURL != "") target.location.href = event.data.targetURL;
            };
        } else {
            console.log('does not support Web Workers...');
        }
    }

    function stopWorker() {
        work.terminate();
    }

    startWorker();

worker:

// 解決ios safari tab在後臺會遭遇進程凍結問題
// http://www.apple.com/safari/#gallery-icloud-tabs
// Safari takes advantage of power-saving technologies such as App Nap, which puts background Safari tabs into a low-power state until you start using them again. In addition, Safari Power Saver conserves battery life by intelligently pausing web videos and other plug‑in content when they’re not front and center on the web pages you visit. All told, Safari on OS X Mavericks lets you browse up to an hour longer than with Chrome or Firefox.1

importScripts('/socket.io/socket.io.js');

var count = 0,
	targetURL = ''
	; 

var socket = io.connect('/');
socket.on('navigate', function (data) {
  count = count++;
  postMessage({targetURL:data.url,count:count});
});

##Web移動端Fixed佈局的解決方案
http://efe.baidu.com/blog/mobile-fixed-layout/

##ios上background-attachment:fixed不能正常工作

參考 http://stackoverflow.com/questions/20443574/fixed-background-image-with-ios7

##如何讓音頻跟視頻在ios跟android上自動播放

<audio autoplay ><source  src="audio/alarm1.mp3" type="audio/mpeg"></audio>

系統默認情況下 audio的autoplay屬性是無法生效的,這也是手機爲節省用戶流量做的考慮。
如果必須要自動播放,有兩種方式可以解決。

1.捕捉一次用戶輸入後,讓音頻加載,下次即可播放。

//play and pause it once
document.addEventListener('touchstart', function () {
    document.getElementsByTagName('audio')[0].play();
    document.getElementsByTagName('audio')[0].pause();
});

這種方法需要捕獲一次用戶的點擊事件來促使音頻跟視頻加載。當加載後,你就可以用javascript控制音頻的播放了,如調用audio.play()

2.利用iframe加載資源

var ifr=document.createElement("iframe");
ifr.setAttribute('src', "http://mysite.com/myvideo.mp4");
ifr.setAttribute('width', '1px');
ifr.setAttribute('height', '1px');
ifr.setAttribute('scrolling', 'no');
ifr.style.border="0px";
document.body.appendChild(ifr);

這種方式其實跟第一種原理是一樣的。當資源加載了你就可以控制播放了,但是這裏使用iframe來加載,相當於直接觸發資源加載。
注意,使用創建audio標籤並讓其加載的方式是不可行的。
慎用這種方法,會對用戶造成很糟糕的影響。。

##iOS 6 跟 iPhone 5 的那些事

###IP5 的媒體查詢

@media (device-height: 568px) and (-webkit-min-device-pixel-ratio: 2) {

/* iPhone 5 or iPod Touch 5th generation */

}

###使用媒體查詢,提供不同的啓動圖片:

<link href="startup-568h.png" rel="apple-touch-startup-image" media="(device-height: 568px)">
<link href="startup.png" rel="apple-touch-startup-image" sizes="640x920" media="(device-height: 480px)">

###拍照上傳

<input type=file accept="video/*">
<input type=file accept="image/*">

不支持其他類型的文件 ,如音頻,Pages文檔或PDF文件。 也沒有getUserMedia攝像頭的實時流媒體支持。

###可以使用的 HTML5 高級 api

  • multipart POST 表單提交上傳
  • XMLHttpRequest 2 AJAX 上傳(甚至進度支持)
  • 文件 API ,在 iOS 6 允許 JavaScript 直接讀取的字節數和客戶端操作文件。

###智能應用程序橫幅

有了智能應用程序橫幅,當網站上有一個相關聯的本機應用程序時,Safari瀏覽器可以顯示一個橫幅。 如果用戶沒有安裝這個應用程序將顯示“安裝”按鈕,或已經安裝的顯示“查看”按鈕可打開它。

在 iTunes Link Maker 搜索我們的應用程序和應用程序ID。

<meta name="apple-itunes-app" content="app-id=9999999">

可以使用 app-argument 提供字符串值,如果參加iTunes聯盟計劃,可以添加元標記數據

<meta name="apple-itunes-app" content="app-id=9999999, app-argument=xxxxxx">

<meta name="apple-itunes-app" content="app-id=9999999, app-argument=xxxxxx, affiliate-data=partnerId=99&siteID=XXXX">

橫幅需要156像素(設備是312 hi-dpi)在頂部,直到用戶在下方點擊內容或關閉按鈕,你的網站纔會展現全部的高度。 它就像HTML的DOM對象,但它不是一個真正的DOM。

CSS3 濾鏡

-webkit-filter: blur(5px) grayscale (.5) opacity(0.66) hue-rotate(100deg);

交叉淡變

background-image: -webkit-cross-fade(url("logo1.png"), url("logo2.png"), 50%);

Safari中的全屏幕

除了chrome-less 主屏幕meta標籤,現在的iPhone和iPod Touch(而不是在iPad)支持全屏幕模式的窗口。 沒有辦法強制全屏模式,它需要由用戶啓動(工具欄上的最後一個圖標)。需要引導用戶按下屏幕上的全屏圖標來激活全屏效果。 可以使用onresize事件檢測是否用戶切換到全屏幕。

支持requestAnimationFrameAPI

支持image-set,retina屏幕的利器

-webkit-image-set(url(low.png) 1x, url(hi.jpg) 2x)

應用程序緩存限制增加至25MB。

Web View(pseudobrowsers,PhoneGap/Cordova應用程序,嵌入式瀏覽器) 上Javascript運行比Safari慢3.3倍(或者說,Nitro引擎在Safari瀏覽器是Web應用程序是3.3倍速度)。

autocomplete屬性的輸入遵循DOM規範

來自DOM4的Mutation Observers已經實現。 您可以使用WebKitMutationObserver構造器捕獲DOM的變化

Safari不再總是對用 -webkit-transform:preserve-3d 的元素創建硬件加速

支持window.selection 的Selection API

Canvas更新 :createImageData有一個參數,現在有兩個新的功能做好準備,用webkitGetImageDataHD和webkitPutImageDataHD提供高分辨率圖像 。

更新SVG處理器和事件構造函數

##IOS7的大更新

iOS 7 的 Safari 和 HTML5:問題,變化和新 API(張金龍翻譯)

iOS 7 的一些坑(英文)

ios7的一些坑2(英文)

##webview相關

#Cache開啓和設置

browser.getSettings().setAppCacheEnabled(true);
browser.getSettings().setAppCachePath("/data/data/[com.packagename]/cache");
browser.getSettings().setAppCacheMaxSize(5*1024*1024); // 5MB

#LocalStorage相關設置

browser.getSettings().setDatabaseEnabled(true);
browser.getSettings().setDomStorageEnabled(true);
String databasePath = browser.getContext().getDir("databases", Context.MODE_PRIVATE).getPath();
browser.getSettings().setDatabasePath(databasePath);//Android webview的LocalStorage有個問題,關閉APP或者重啓後,就清楚了,所以需要browser.getSettings().setDatabase相關的操作,把LocalStoarge存到DB中

myWebView.setWebChromeClient(new WebChromeClient(){
    @Override
    public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater)
    {
        quotaUpdater.updateQuota(estimatedSize * 2);
    }
}

#瀏覽器自帶縮放按鈕取消顯示

browser.getSettings().setBuiltInZoomControls(false);

#幾個比較好的實踐

使用localstorage緩存html

使用lazyload,還要記得lazyload佔位圖雖然小,但是最好能提前加載到緩存

延時加載執行js

主要原因就在於Android Webview的onPageFinished事件,Android端一般是用這個事件來標識頁面加載完成並顯示的,也就是說在此之前,會一直loading,但是Android的OnPageFinished事件會在Javascript腳本執行完成之後纔會觸發。如果在頁面中使用JQuery,會在處理完DOM對象,執行完$(document).ready(function() {});事件自會後纔會渲染並顯示頁面。

###manifest與緩存相關:
http://www.alloyteam.com/2013/12/web-cache-6-hybrid-app-tailored-cache/
相關解決方案
http://mt.tencent.com/

##移動端調適篇

###手機抓包與配host

在PC上,我們可以很方便地配host,但是手機上如何配host,這是一個問題。

這裏主要使用fiddler和遠程代理,實現手機配host的操作,具體操作如下:

首先,保證PC和移動設備在同一個局域網下;

PC上開啓fiddler,並在設置中勾選“allow remote computers to connect”

  1. 首先,保證PC和移動設備在同一個局域網下;

  2. PC上開啓fiddler,並在設置中勾選“allow remote computers to connect”
    fiddler

  3. 手機上設置代理,代理IP爲PC的IP地址,端口爲8888(這是fiddler的默認端口)。通常手機上可以直接設置代理,如果沒有,可以去下載一個叫ProxyDroid的APP來實現代理的設置。

  4. 此時你會發現,用手機上網,走的其實是PC上的fiddler,所有的請求包都會在fiddler中列出來,配合willow使用,即可實現配host,甚至是反向代理的操作。

也可以用CCProxy之類軟件,還有一種方法就是買一個隨身wifi,然後手機連接就可以了!

###高級抓包

iPhone上使用Burp Suite捕捉HTTPS通信包方法

mobile app 通信分析方法小議(iOS/Android)

實時抓取移動設備上的通信包(ADVsock2pipe+Wireshark+nc+tcpdump)

###靜態資源緩存問題

一般用代理軟件代理過來的靜態資源可以設置nocache避免緩存,但是有的手機比較詭異,會一直緩存住css等資源文件。由於靜態資源一般都是用版本號管理的,我們以charles爲例子來處理這個問題

charles 選擇靜態的html頁面文件-saveResponse。之後把這個文件保存一下,修改一下版本號。之後繼續發請求,
剛纔的html頁面文件 右鍵選擇 --map local 選擇我們修改過版本號的html文件即ok。這其實也是fiddler遠程映射並修改文件的一個應用場景。

###安卓模擬器和真機區別

http://www.farsight.com.cn/news/emb105.htm

http://testerhome.com/topics/388

http://www.cnblogs.com/zdz8207/archive/2012/01/30/2332436.html

##移動瀏覽器篇

###微信瀏覽器

微信瀏覽器的各種bug彙總 (x5內核) http://www.qianduan.net/qqliu-lan-qi-x5nei-he-wen-ti-hui-zong/

因爲微信瀏覽器屏蔽了一部分鏈接圖片,所以需要引導用戶去打開新頁面,可以用以下方式判斷微信瀏覽器的ua

function is_weixn(){
    var ua = navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i)=="micromessenger") {
        return true;
    } else {
        return false;
    }
}

後端判斷也很簡單,比如php

function is_weixin(){
    if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return true;
    }  
    return false;
}

maxzhang/maxzhang.github.com#31 微信瀏覽器踩坑,來自maxZhang https://github.com/maxzhang

###【UC瀏覽器】video標籤脫離文檔流

場景:標籤的父元素(祖輩元素)設置transform樣式後,標籤會脫離文檔流。

測試環境:UC瀏覽器 8.7/8.6 + Android 2.3/4.0 。

Demo:http://t.cn/zj3xiyu

解決方案:不使用transform屬性。translate用top、margin等屬性替代。

###【UC瀏覽器】video標籤總在最前

場景:標籤總是在最前(可以理解爲video標籤的z-index屬性是Max)。

測試環境:UC瀏覽器 8.7/8.6 + Android 2.3/4.0 。

###【UC瀏覽器】position:fixed 屬性在UC瀏覽器的奇葩現象

場景:設置了position: fixed 的元素會遮擋z-index值更高的同輩元素。

   在8.6的版本,這個情況直接出現。

   在8.7之後的版本,當同輩元素的height大於713這個「神奇」的數值時,纔會被遮擋。

測試環境:UC瀏覽器 8.8_beta/8.7/8.6 + Android 2.3/4.0 。

Demo:http://t.cn/zYLTSg6

###【QQ手機瀏覽器】不支持HttpOnly

場景:帶有HttpOnly屬性的Cookie,在QQ手機瀏覽器版本從4.0開始失效。JavaScript可以直接讀取設置了HttpOnly的Cookie值。

測試環境:QQ手機瀏覽器 4.0/4.1/4.2 + Android 4.0 。

###【MIUI原生瀏覽器】瀏覽器地址欄hash不改變

場景:location.hash 被賦值後,地址欄的地址不會改變。

   但實際上 location.href 已經更新了,通過JavaScript可以順利獲取到更新後的地址。

   雖然不影響正常訪問,但用戶無法將訪問過程中改變hash後的地址存爲書籤。

測試環境:MIUI 4.0

###【Chrome Mobile】fixed元素無法點擊

場景:父元素設置position: fixed;

   子元素設置position: absolute;

   此時,如果父元素/子元素還設置了overflow: hidden 則出現“父元素遮擋該子元素“的bug。

   視覺(view)層並沒有出現遮擋,只是無法觸發綁定在該子元素上的事件。可理解爲:「看到點不到」。

補充: 頁面往下滾動,觸發position: fixed;的特性時,纔會出現這個bug,在最頂不會出現。

測試平臺: 小米1S,Android4.0的Chrome18

demo: http://maplejan.sinaapp.com/demo/fixed_chromemobile.html

解決辦法: 把父元素和子元素的overflow: hidden去掉。

以上來源於 http://www.cnblogs.com/maplejan/archive/2013/04/26/3045928.html

##庫的使用實踐

###zepto.js

zepto的一篇使用注意點講解

zepto的著名的tap“點透”bug

zepto源碼註釋

###使用zeptojs內嵌到android webview影響正常滾動時
https://github.com/madrobby/zepto/blob/master/src/touch.js 去掉61行,其實就是使用原生的滾動

###iscroll4

iscroll4 的幾個bug(來自 http://www.mansonchor.com/blog/blog_detail_64.html 內有詳細講解)

1.滾動容器點擊input框、select等表單元素時沒有響應】

onBeforeScrollStart: function (e) { e.preventDefault(); }

改爲

onBeforeScrollStart: function (e) { var nodeType = e.explicitOriginalTarget © e.explicitOriginalTarget.nodeName.toLowerCase():(e.target © e.target.nodeName.toLowerCase():'');if(nodeType !='select'&& nodeType !='option'&& nodeType !='input'&& nodeType!='textarea') e.preventDefault(); }

2.往iscroll容器內添加內容時,容器閃動的bug

源代碼的

has3d = 'WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix()

改成

has3d = false

在配置iscroll時,useTransition設置成false

3.過長的滾動內容,導致卡頓和app直接閃退

  1. 不要使用checkDOMChanges。雖然checkDOMChanges很方便,定時檢測容器長度是否變化來refresh,但這也意味着你要消耗一個Interval的內存空間
  2. 隱藏iscroll滾動條,配置時設置hScrollbar和vScrollbar爲false。
  3. 不得已的情況下,去掉各種效果,momentum、useTransform、useTransition都設置爲false

4.左右滾動時,不能正確響應正文上下拉動

iscroll的閃動問題也與渲染有關係,可以參考
運用webkit繪製渲染頁面原理解決iscroll4閃動的問題
iscroll4升級到5要注意的問題

###iscroll或者滾動類框架滾動時不點擊的方法

可以使用以下的解決方案(利用data-setapi)

<a ontouchmove="this.s=1" ontouchend="this.s || window.open(this.dataset.href),this.s=0" target="_blank" data-href="http://www.hao123.com/topic/pig">黃浦江死豬之謎</a>

也可以用這種方法

	$(document).delegate('[data-target]', 'touchmove', function () {
		$(this).attr('moving','moving');

	})
	

	$(document).delegate('[data-target]', 'touchend', function () {
		if ($(this).attr('moving') !== 'moving') {
		 //做你想做的。。
			$(this).attr('moving', 'notMoving');
		} else {
			$(this).attr('moving', 'notMoving');
		}

	})

##移動端字體問題

知乎專欄 - [無線手冊-4] dp、sp、px傻傻分不清楚[完整]

Resolution Independent Mobile UI

Pixel density, retina display and font-size in CSS

Device pixel density tests

##跨域問題

手機瀏覽器也是瀏覽器,在ajax調用外部api的時候也存在跨域問題。當然利用 PhoneGap 打包後,由於協議不一樣就不存在跨域問題了。
但頁面通常是需要跟後端進行調試的。一般會報類似

XMLHttpRequest cannot load XXX
Origin null is not allowed by Access-Control-Allow-Origin.

以及

XMLHttpRequest cannot load http://. Request header field Content-Type is not allowed by Access-Control-Allow-Headers."

這時候可以讓後端加上兩個http頭

Access-Control-Allow-Origin "*"
Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"

第一個頭可以避免跨域問題,第二個頭可以方便ajax請求設置content-type等配置項

這個會存在一些安全問題,可以參考這個問題的討論 http://www.zhihu.com/question/22992229

##PhoneGap 部分

http://snoopyxdy.blog.163.com/blog/static/60117440201432491123551 這裏有一大堆snoopy總結的phonggap開發坑

###Should not happen: no rect-based-test nodes found
在 Android 項目中的 assets 中的 HTML 頁面中加入以下代碼,便可解決問題

window,html,body{
    overflow-x:hidden !important;
    -webkit-overflow-scrolling: touch !important;
    overflow: scroll !important;
}

參考:

http://stackoverflow.com/questions/12090899/android-webview-jellybean-should-not-happen-no-rect-based-test-nodes-found

###拿聯繫人的時候報 ContactFindOptions is not defined

出現這個問題可能是因爲 Navigator 取 contacts 時綁定的 window.onload

注意使用 PhoneGap 的 API 時,一定要在 devicereay 事件的處理函數中使用 API

document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {    
        callFetchContacts();
    }

function callFetchContacts(){
    var options = new ContactFindOptions();
    options.multiple = true;
    var fields       = ["displayName", "name","phoneNumbers"];
    navigator.contacts.find(fields, onSuccess, onError,options);  
    } 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章