本文來源: http://www.zhangxinxu.com/study/201312/js-parabola-shopping.htmljavascript
parabola.jsphp
/*! * by zhangxinxu(.com) 2012-12-27 * you can visit http://www.zhangxinxu.com/wordpress/?p=3855 to get more infomation * under MIT license */ var funParabola = function(element, target, options) { /* * 網頁模擬現實須要一個比例尺 * 若是按照1像素就是1米來算,顯然不合適,由於頁面動不動就幾百像素 * 頁面上,咱們放兩個物體,200~800像素之間,咱們能夠映射爲現實世界的2米到8米,也就是100:1 * 不過,本方法沒有對此有所體現,所以沒必要在乎 */ var defaults = { speed: 166.67, // 每幀移動的像素大小,每幀(對於大部分顯示屏)大約16~17毫秒 curvature: 0.001, // 實際指焦點到準線的距離,你能夠抽象成曲率,這裏模擬扔物體的拋物線,所以是開口向下的 progress: function() {}, complete: function() {} }; var params = {}; options = options || {}; for (var key in defaults) { params[key] = options[key] || defaults[key]; } var exports = { mark: function() { return this; }, position: function() { return this; }, move: function() { return this; }, init: function() { return this; } }; /* 肯定移動的方式 * IE6-IE8 是margin位移 * IE9+使用transform */ var moveStyle = "margin", testDiv = document.createElement("div"); if ("oninput" in testDiv) { ["", "ms", "webkit"].forEach(function(prefix) { var transform = prefix + (prefix? "T": "t") + "ransform"; if (transform in testDiv.style) { moveStyle = transform; } }); } // 根據兩點座標以及曲率肯定運動曲線函數(也就是肯定a, b的值) /* 公式: y = a*x*x + b*x + c; */ var a = params.curvature, b = 0, c = 0; // 是否執行運動的標誌量 var flagMove = true; if (element && target && element.nodeType == 1 && target.nodeType == 1) { var rectElement = {}, rectTarget = {}; // 移動元素的中心點位置,目標元素的中心點位置 var centerElement = {}, centerTarget = {}; // 目標元素的座標位置 var coordElement = {}, coordTarget = {}; // 標註當前元素的座標 exports.mark = function() { if (flagMove == false) return this; if (typeof coordElement.x == "undefined") this.position(); element.setAttribute("data-center", [coordElement.x, coordElement.y].join()); target.setAttribute("data-center", [coordTarget.x, coordTarget.y].join()); return this; } exports.position = function() { if (flagMove == false) return this; var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft, scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // 初始位置 if (moveStyle == "margin") { element.style.marginLeft = element.style.marginTop = "0px"; } else { element.style[moveStyle] = "translate(0, 0)"; } // 四邊緣的座標 rectElement = element.getBoundingClientRect(); rectTarget = target.getBoundingClientRect(); // 移動元素的中心點座標 centerElement = { x: rectElement.left + (rectElement.right - rectElement.left) / 2 + scrollLeft, y: rectElement.top + (rectElement.bottom - rectElement.top) / 2 + scrollTop }; // 目標元素的中心點位置 centerTarget = { x: rectTarget.left + (rectTarget.right - rectTarget.left) / 2 + scrollLeft, y: rectTarget.top + (rectTarget.bottom - rectTarget.top) / 2 + scrollTop }; // 轉換成相對座標位置 coordElement = { x: 0, y: 0 }; coordTarget = { x: -1 * (centerElement.x - centerTarget.x), y: -1 * (centerElement.y - centerTarget.y) }; /* * 由於通過(0, 0), 所以c = 0 * 因而: * y = a * x*x + b*x; * y1 = a * x1*x1 + b*x1; * y2 = a * x2*x2 + b*x2; * 利用第二個座標: * b = (y2+ a*x2*x2) / x2 */ // 因而 b = (coordTarget.y - a * coordTarget.x * coordTarget.x) / coordTarget.x; return this; }; // 按照這個曲線運動 exports.move = function() { // 若是曲線運動尚未結束,再也不執行新的運動 if (flagMove == false) return this; var startx = 0, rate = coordTarget.x > 0? 1: -1; var step = function() { // 切線 y'=2ax+b var tangent = 2 * a * startx + b; // = y / x // y*y + x*x = speed // (tangent * x)^2 + x*x = speed // x = Math.sqr(speed / (tangent * tangent + 1)); startx = startx + rate * Math.sqrt(params.speed / (tangent * tangent + 1)); // 防止過界 if ((rate == 1 && startx > coordTarget.x) || (rate == -1 && startx < coordTarget.x)) { startx = coordTarget.x; } var x = startx, y = a * x * x + b * x; // 標記當前位置,這裏有測試使用的嫌疑,實際使用能夠將這一行註釋 element.setAttribute("data-center", [Math.round(x), Math.round(y)].join()); // x, y目前是座標,須要轉換成定位的像素值 if (moveStyle == "margin") { element.style.marginLeft = x + "px"; element.style.marginTop = y + "px"; } else { element.style[moveStyle] = "translate("+ [x + "px", y + "px"].join() +")"; } if (startx !== coordTarget.x) { params.progress(x, y); window.requestAnimationFrame(step); } else { // 運動結束,回調執行 params.complete(); flagMove = true; } }; window.requestAnimationFrame(step); flagMove = false; return this; }; // 初始化方法 exports.init = function() { this.position().mark().move(); }; } return exports; }; /*! requestAnimationFrame.js * by zhangxinxu 2013-09-30 */ (function() { var lastTime = 0; var vendors = ['webkit', 'moz']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || // name has changed in Webkit window[vendors[x] + 'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) { window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16.7 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } if (!window.cancelAnimationFrame) { window.cancelAnimationFrame = function(id) { clearTimeout(id); }; } }());
案例htmlcss
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="description" content="JS拋物線動畫與購物車效果 » 張鑫旭-鑫空間-鑫生活" /> <meta name="description" content="張鑫旭web前端學習實例頁面 JS拋物線動畫與購物車效果" /> <meta name="keywords" content="拋物線, 動畫, javascript" /> <meta name="author" content="張鑫旭, zhangxixnu" /> <title>JS拋物線動畫與購物車效果 » 張鑫旭-鑫空間-鑫生活</title> <link rel="stylesheet" href="../css/demo.css" type="text/css" /> <link rel="stylesheet" href="../css/hl.css" type="text/css" /> <style> body { overflow-x: hidden; } img { vertical-align: bottom; } .width_limit { width: 1194px; margin-left: auto; margin-right: auto; } .image_limit { position: relative; } .shop_cart { width: 283px; height: 25px; line-height: 25px; padding-top: 8px; background: url(shopping-cart.png); font-family: 'microsoft yahei'; font-size: 12px; text-indent: 34px; color: #000; position: fixed; right: 10px; bottom: 0; } .add_cart_large, .add_cart_small { position: absolute; background: url(about:blank); text-indent: -99em; overflow: hidden; } .add_cart_large { width: 167px; height: 33px; left: 724px; top: 511px; } .add_cart_small { width: 82px; height: 25px; left: 1098px; top: 1014px; } .fly_item { border: 2px solid #B30000; width: 50px; height: 50px; overflow: hidden; position: absolute; visibility: hidden; opacity: .5; filter: alpha(opacity=50); } </style> </head> <body> <div id="header"> <a href="/" class="logo" title="回到鑫空間-鑫生活首頁"> <img src="http://www.zhangxinxu.com/php/image/zxx_home_logo.png" border="0" /> </a> </div> <div id="main"> <h1>JS拋物線動畫與購物車效果實例頁面</h1> <div id="body" class="light"> <div id="content" class="show"> <h3>展現</h3> <div class="article_new"><a href="http://www.zhangxinxu.com/wordpress/?p=3855">回到相關文章 »</a></div> <div class="demo"> <div class="width_limit"> <p>下面這個是截圖,只有兩個「加入購物車」按鈕能夠點擊:</p> <div class="image_limit"> <img src="http://image.zhangxinxu.com/image/blog/201412/2013-12-30_103800.png" width="1194" height="1051" alt="天貓某商品頁面的部分截圖" /> <a href="javascript:" class="add_cart_large btnCart" title="加入購物車">加入購物車</a> <a href="javascript:" class="add_cart_small btnCart" title="加入購物車">加入購物車</a> </div> </div> <div id="shopCart" class="shop_cart">購物車 <span>0</span></div> <div id="flyItem" class="fly_item"><img src="/study/201312/item-pic.jpg" width="50" height="50" /></div> </div> <h3>代碼</h3> <h5>JS代碼:</h5> <pre name="code" class="js"> /* 本demo演示腳本基於ieBetter.js, 項目地址:https://github.com/zhangxinxu/ieBetter.js */ // 元素以及其餘一些變量 var eleFlyElement = document.querySelector("#flyItem"), eleShopCart = document.querySelector("#shopCart"); var numberItem = 0; // 拋物線運動 var myParabola = funParabola(eleFlyElement, eleShopCart, { speed: 400, curvature: 0.002, complete: function() { eleFlyElement.style.visibility = "hidden"; eleShopCart.querySelector("span").innerHTML = ++numberItem; } }); // 綁定點擊事件 if (eleFlyElement && eleShopCart) { [].slice.call(document.getElementsByClassName("btnCart")).forEach(function(button) { button.addEventListener("click", function() { // 滾動大小 var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft || 0, scrollTop = document.documentElement.scrollTop || document.body.scrollTop || 0; eleFlyElement.style.left = event.clientX + scrollLeft + "px"; eleFlyElement.style.top = event.clientY + scrollTop + "px"; eleFlyElement.style.visibility = "visible"; // 須要重定位 myParabola.position().move(); }); }); } </pre> </div> </div> </div> <script src="http://rawgithub.com/zhangxinxu/ieBetter.js/master/ieBetter.js"></script> <script src="/study/201312/parabola.js"></script> <script> // 元素以及其餘一些變量 var eleFlyElement = document.querySelector("#flyItem"), eleShopCart = document.querySelector("#shopCart"); var numberItem = 0; // 拋物線運動 var myParabola = funParabola(eleFlyElement, eleShopCart, { speed: 400, curvature: 0.002, complete: function() { eleFlyElement.style.visibility = "hidden"; eleShopCart.querySelector("span").innerHTML = ++numberItem; } }); // 綁定點擊事件 if (eleFlyElement && eleShopCart) { [].slice.call(document.getElementsByClassName("btnCart")).forEach(function(button) { button.addEventListener("click", function(event) { // 滾動大小 var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft || 0, scrollTop = document.documentElement.scrollTop || document.body.scrollTop || 0; eleFlyElement.style.left = event.clientX + scrollLeft + "px"; eleFlyElement.style.top = event.clientY + scrollTop + "px"; eleFlyElement.style.visibility = "visible"; // 須要重定位 myParabola.position().move(); }); }); } </script> <!-- 如下腳本是可有可無 --> <script type="text/javascript" src="../js/hl_all.js"></script> <script type="text/javascript"> DlHighlight.HELPERS.highlightByName("code", "pre"); </script> <div id="footer"> Designed & Powerd by <a href="http://www.zhangxinxu.com/">zhangxinxu</a><br /> Copyright© 張鑫旭-鑫空間-鑫生活<br> <a href="http://www.miibeian.gov.cn/" target="_blank">鄂ICP備09015569號</a> </div> <div id="ad"> <script type="text/javascript"> google_ad_client = "pub-0090627341039040";google_ad_slot = "2041257798";google_ad_width = 468;google_ad_height = 60;</script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-11205167-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'http://www.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </div> </body> </html>