本文實例講述了如何用 JS 處理 transition 和 transform 的瀏覽器兼容問題,分享給大家供參考。
今天在純手工打造 JS 圖片滾動效果時,遇到了一個惱人的兼容問題。
之前設置圖片滾動動畫的方式如下:
var addSlideStyle = function(time, leftWidth) { time = time || 0; leftWidth = leftWidth || 0; return 'transition: all ' + time + 's ease-in-out; transform: translate3d(' + leftWidth + 'px, 0px, 0px);'; };
使用方式:
slideUlObj.style = addSlideStyle();
這種用 js 拼接 style 字符串的方式在 PC 端一切正常,可以自動滾動,可一到手機上各種不兼容就出來了,即使在 addSlideStyle 裡加上 -webkit- 前綴也無效。
搜尋後確認是 mobile 端的兼容問題,於是改為逐個設置動畫屬性:
var setTransition = function(obj, time) { time = time || 0; var style = 'all ' + time + 's ease-in-out'; obj.style.webkitTransition = style; obj.style.transition = style; }; var setTransform = function(obj, leftWidth) { leftWidth = leftWidth || 0; var style = 'translate3d(' + leftWidth + 'px, 0px, 0px)'; obj.style.webkitTransform = style; obj.style.transform = style; }; var setAnimate = function(obj, time, leftWidth) { setTransition(obj, time); setTransform(obj, leftWidth); };
調用方式:
setAnimate(slideUlObj);
設置各種瀏覽器兼容性格式的順序如下:
webkitProperty MozProperty msProperty OProperty property
調用示例:
element.style.webkitTransform = ""; element.style.MozTransform = ""; element.style.msTransform = ""; element.style.OTransform = ""; element.style.transform = "";
核心思路是:不要用字符串一次性賦值 style,而是針對每個瀏覽器前綴的屬性逐一賦值,這樣才能在各平台上正確生效。希望本文對大家的 JavaScript 開發有所幫助。