JS实现多图点击切换,鼠标移上放大

开发 前端
次采用代码封装到一个对象的模式,和第一次函数式写法不一下,这样更清晰,添加自定义属性更方便,全部代码如下。

继 javascript 简单的图片放大效果(一) 之后,把这个效果完善了一下,支持多图轮流切换,如下:

本次采用代码封装到一个对象的模式,和***次函数式写法不一下,这样更清晰,添加自定义属性更方便,全部代码如下:

大图的地址用自定义属性的方式显示在<img>标签如

  1. <li><img src="images/small.jpg" width="70" height="70" zoom="images/big.jpg"></li> 
 
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
  2. <html xmlns="http://www.w3.org/1999/xhtml"> 
  3. <head> 
  4.     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 
  5.     <title>图片放大实例</title> 
  6.     <script type="text/javascript" src="js/vvgbase.1.0.js"></script> 
  7.     <style type="text/css"> 
  8.         * {  
  9.             margin: 0;  
  10.             padding: 0;  
  11.         }  
  12.  
  13.         #zoomWarp {  
  14.             width: 1000px;  
  15.             margin: 20px auto;  
  16.             overflow: hidden;  
  17.         }  
  18.  
  19.         #smallwarp {  
  20.             position: relative;  
  21.             border: 1px solid #000;  
  22.             width: 300px;  
  23.             height: 300px;  
  24.             float: left;  
  25.             overflow: hidden;  
  26.         }  
  27.  
  28.         #minImg {  
  29.             float: left;  
  30.             display: inline;  
  31.             margin-right: 5px;  
  32.         }  
  33.  
  34.         #minImg li {  
  35.             width: 70px;  
  36.             height: 70px;  
  37.             overflow: hidden;  
  38.             background: #ccc;  
  39.             margin-bottom: 5px;  
  40.             border: 1px solid #333;  
  41.             cursor: pointer;  
  42.             list-style: none;  
  43.         }  
  44.  
  45.         #minImg li.lastChild {  
  46.             margin-bottom: 0;  
  47.         }  
  48.     </style> 
  49. </head> 
  50. <body> 
  51. <iframe src="http://greencat.w211141.fxdns.cn/jsplay/ImgZoomTest.html"></iframe> 
  52. <div id="zoomWarp"> 
  53.     <ul id="minImg"> 
  54.         <li><img src="images/small.jpg" width="70" height="70" zoom="images/big.jpg"></li> 
  55.         <li><img src="images/small1.jpg" width="70" height="70" zoom="images/big1.jpg"></li> 
  56.         <li><img src="images/small.jpg" width="70" height="70" zoom="images/big.jpg"></li> 
  57.         <li class="lastChild"><img src="images/small1.jpg" width="70" height="70" zoom="images/big1.jpg"></li> 
  58.     </ul> 
  59.     <div id="smallwarp"> 
  60.         <img src="images/small.jpg" id="smallImg" zoom="images/big.jpg"/> 
  61.     </div> 
  62. </div> 
  63. <script type="text/javascript"> 
  64.     var zoomImg = function () {  
  65.         return {  
  66.             init:function (warpId, options) {  
  67.                 this.zoomWarp = VVG.$(warpId); //获取外层包裹层  
  68.                 var sWarp = options.smallWarp || 'smallwarp'; //小图包裹层ID  
  69.                 var smallWarp = this.smallWarp = VVG.$(sWarp); //获取小图包裹层  
  70.                 this.targetImg = VVG.$$('img', smallWarp)[0];  //获取放大的目标图片对象  
  71.                 thisthis.bigImgUrl = this.targetImg.getAttribute('zoom'); //从目标图片对象的自定义属性读取大图的URL  
  72.                 this.bindMove();  
  73.                 this.bindMinImg();  
  74.             },  
  75.             createMask:function () {  
  76.                 var mask = this.mask = document.createElement("div"); //创建MASK层  
  77.                 mask.id = "mask";  
  78.                 // 设置CSS  
  79.                 VVG.setStyleById(mask, {  
  80.                     "position":"absolute",  
  81.                     "z-index":100,  
  82.                     "display":"none",  
  83.                     "width":"100px",  
  84.                     "height":"100px",  
  85.                     "background":"#999",  
  86.                     "border":"1px solid #000",  
  87.                     "cursor":"crosshair",  
  88.                     "opacity":80,  
  89.                     "left":0,  
  90.                     "top":0  
  91.                 });  
  92.                 this.smallWarp.appendChild(mask); //添加MASK层  
  93.             },  
  94.             createBigDiv:function () {  
  95.                 var bigDiv = this.bigDiv = document.createElement("div"); //创建大图显示层  
  96.                 bigDiv.id = "big";  
  97.                 VVG.setStyleById(bigDiv, {  
  98.                     "float":"left",  
  99.                     "border":"1px solid #000",  
  100.                     "display":"none",  
  101.                     "width":"300px",  
  102.                     "height":"300px",  
  103.                     "overflow":"hidden",  
  104.                     "border-left":"none",  
  105.                     "position":"relative",  
  106.                     "z-index":"100"  
  107.                 });  
  108.                 // 创建大图  
  109.                 var bigImg = this.bigImg = document.createElement('img');  
  110.                 bigImg.setAttribute('src', this.bigImgUrl);  
  111.                 bigImg.id = 'bigImg';  
  112.                 bigImg.style.position = 'absolute';  
  113.                 bigDiv.appendChild(bigImg);  
  114.                 this.zoomWarp.appendChild(bigDiv); //添加大图显示层  
  115.             },  
  116.             show:function () { // 显示悬浮遮罩层和放大图片层  
  117.                 this.mask.style.display = 'block';  
  118.                 this.bigDiv.style.display = 'block';  
  119.             },  
  120.             hidden:function () { //隐藏层  
  121.                 this.mask.style.display = 'none';  
  122.                 this.bigDiv.style.display = 'none';  
  123.             },  
  124.             zoomIng:function (event) { //开始放大  
  125.                 this.show(); //显示  
  126.                 event = VVG.getEvent(event); //获取事件  
  127.                 var target = this.mask;  
  128.                 var maskW = target.offsetWidth;  
  129.                 var maskH = target.offsetHeight;  
  130.                 //console.log(maskW +':'+maskH);  
  131.                 var sTop = document.documentElement.scrollTop || document.body.scrollTop;  
  132.                 var mouseX = event.clientX;  
  133.                 var mouseY = event.clientY + sTop;  
  134.                 var smallX = this.smallWarp.offsetLeft;  
  135.                 var smallY = this.smallWarp.offsetTop;  
  136.                 var smallW = this.smallWarp.offsetWidth;  
  137.                 var smallH = this.smallWarp.offsetHeight;  
  138.                 //console.log('x=' + mouseX + ':y=' + mouseY + ':' + sTop + 'smallX:' + smallX);  
  139.                 target.style.left = (mouseX - smallX - maskW / 2 ) + "px";  
  140.                 target.style.top = (mouseY - smallY - maskH / 2 ) + "px";  
  141.                 //显示位置计算  
  142.                 if ((mouseX - smallX) < maskW / 2) {  
  143.                     target.style.left = "0px";  
  144.                 } else if ((mouseX - smallX) > (smallW - maskW + maskW / 2)) {  
  145.                     target.style.left = (smallW - maskW ) + "px";  
  146.                 }  
  147.                 if ((mouseY - smallY) < maskH / 2) {  
  148.                     target.style.top = "0px";  
  149.                 } else if ((mouseY - smallY) > (smallH - maskH + maskH / 2)) {  
  150.                     target.style.top = (smallH - maskH) + "px";  
  151.                 }  
  152.                 this.showBig(parseInt(target.style.left), parseInt(target.style.top));  
  153.             },  
  154.             showBig:function (left, top) {  
  155.                 left = Math.ceil(left * 3);  
  156.                 top = Math.ceil(top * 3);  
  157.                 this.bigImg.style.left = -left + "px";  
  158.                 this.bigImg.style.top = -top + "px";  
  159.             },  
  160.             bindMove:function () {  
  161.                 this.createMask();  
  162.                 this.createBigDiv();  
  163.                 VVG.bindEvent(this.smallWarp, 'mousemove', VVG.bindFunction(this, this.zoomIng));  
  164.                 VVG.bindEvent(this.smallWarp, 'mouseout', VVG.bindFunction(this, this.hidden));  
  165.             },  
  166.             // 以下是左侧小图鼠标放上去后右侧显示相应的大图  
  167.             bindMinImg:function () {  
  168.                 var minImgUl = VVG.$('minImg'); //获取左侧的UL  
  169.                 var minImgLis = VVG.$$('li', minImgUl); //获取左侧的li  
  170.                 var thisthisObj = this; //this 赋值  
  171.                 for (var i = 0n = minImgLis.length; i < n; i++) {  
  172.                     var liImg = VVG.$$('img', minImgLis[i])[0];  
  173.                     var imgSrc = liImg.src;  
  174.                     var bImgSrc = liImg.getAttribute('zoom');  
  175.                     //以下闭包传值imgSrc,与bImgSrc,并绑定左侧迷你图点击事件  
  176.                     VVG.bindEvent(liImg, 'click', function (t,f) {  
  177.                         return function () {  
  178.                             thisObj.changeImg.call(thisObj,t,f); //此处调用changeImg方法  
  179.                         }  
  180.                     }(imgSrc,bImgSrc));  
  181.                 }  
  182.             },  
  183.             changeImg:function (imgSrc, bImgSrc) { //改变右边的图片地址  
  184.                 this.targetImg.src = imgSrc;  
  185.                 this.bigImg.setAttribute('src', bImgSrc);  
  186.             }  
  187.  
  188.         }  
  189.     }();  
  190.     zoomImg.init('zoomWarp', {});  
  191. </script> 
  192. </body> 
  193. </html> 

#p#

VVG.base库代码:

  1. /*  
  2.  *    简单JS库封装  By VVG  
  3.  *    @namespace VVG  
  4.  *    E-mail:mysheller@163.com    QQ:83816819  
  5.  */  
  6. if (!String.trim) {  
  7.     String.prototype.trim = function () {  
  8.         var reg = /^\s+|\s+$/g;  
  9.         return this.replace(reg, '');  
  10.     }  
  11. }  
  12. (function () {  
  13.     // create namespace VVG  
  14.     if (!window.VVG) {  
  15.         window.VVG = {};  
  16.     }  
  17.  
  18.     function isCompatible(other) {  
  19.         // Use capability detection to check requirements  
  20.         if (other === false || !Array.prototype.push || !Object.hasOwnProperty || !document.createElement || !document.getElementsByTagName) {  
  21.             alert('你的浏览器不支持某些特性!');  
  22.             return false;  
  23.         }  
  24.         return true;  
  25.     }  
  26.  
  27.     window.VVG.isCompatible = isCompatible;  
  28.  
  29.  
  30.     // getElementById function  
  31.  
  32.     function $() {  
  33.         var elements = new Array();  
  34.         for (var i = 0; i < arguments.length; i++) {  
  35.             var element = arguments[i];  
  36.             if (typeof element == 'string') {  
  37.                 element = document.getElementById(element);  
  38.             }  
  39.             if (!element) {  
  40.                 continue;  
  41.             }  
  42.             // 如果只有一个参数,则返回  
  43.             if (arguments.length == 1) {  
  44.                 return element;  
  45.             }  
  46.             // 多个参数的时候存为数组  
  47.             elements.push(element);  
  48.         }  
  49.         // 返回数组  
  50.         return elements;  
  51.     }  
  52.  
  53.     window.VVG.$ = $;  
  54.  
  55.     // 获取Parent父元素下标签名为child 的 Tags  
  56.  
  57.     function $$(tag, parent) {  
  58.         parentparent = parent || document;  
  59.         return $(parent).getElementsByTagName(tag);  
  60.     }  
  61.  
  62.     window.VVG.$$ = $$;  
  63.  
  64.     // getElementsByClassName  
  65.  
  66.     function $$$(str, parent, tag) {  
  67.         //父节点存在  
  68.         if (parent) {  
  69.             parent = $(parent);  
  70.         } else {  
  71.             // 未传值时,父节点为body  
  72.             parent = document;  
  73.         }  
  74.         // tagContent为节点类型,未传值时为all节点  
  75.         tagtag = tag || '*';  
  76.         // 在父节点查找子节点,建立空数组arr  
  77.         var els = parent.getElementsByTagName(tag),  
  78.             arr = [];  
  79.         for (var i = 0n = els.length; i < n; i++) {  
  80.             // 查找每个节点下的classname,以空格分离为一个k数组  
  81.             for (var j = 0k = els[i].className.split(' '), l = k.length; j < 1; j++) {  
  82.                 // 当K数组中有一个值与str值相等时,记住这个标签并推入arr数组  
  83.                 if (k[j] == str) {  
  84.                     arr.push(els[i]);  
  85.                     break;  
  86.                 }  
  87.             }  
  88.         }  
  89.         // 返回数组  
  90.         return arr;  
  91.     }  
  92.  
  93.     window.VVG.$$$ = $$$;  
  94.     window.VVG.getElementsByClassName = $$$;  
  95.  
  96.     // Event事件绑定:绑定type事件到element元素,触发func函数  
  97.  
  98.     function bindEvent(element, type, func) {  
  99.         if (element.addEventListener) {  
  100.             element.addEventListener(type, func, false); //false 表示冒泡  
  101.         } else if (element.attachEvent) {  
  102.             element.attachEvent('on' + type, func);  
  103.         } else {  
  104.             element['on' + type] = func;  
  105.         }  
  106.     }  
  107.  
  108.     window.VVG.bindEvent = bindEvent;  
  109.  
  110.     // 解除Event事件绑定  
  111.  
  112.     function unbindEvent(element, type, func) {  
  113.         if (element.removeEventListener) {  
  114.             element.removeEventListener(type, func, false);  
  115.         } else if (element.detachEvent) {  
  116.             element.detachEvent('on' + type, func);  
  117.         } else {  
  118.             element['on' + type] = null;  
  119.         }  
  120.     }  
  121.  
  122.     window.VVG.unbindEvent = unbindEvent;  
  123.  
  124.     // 获取事件  
  125.  
  126.     function getEvent(event) {  
  127.         return event || window.event;  
  128.     }  
  129.  
  130.     window.VVG.getEvent = getEvent;  
  131.  
  132.     // 获取事件目标  
  133.  
  134.     function getTarget(event) {  
  135.         return event.target || event.srcElement;  
  136.     }  
  137.  
  138.     window.VVG.getTarget = getTarget;  
  139.  
  140.     // 获取鼠标位于文档的坐标  
  141.  
  142.     function getMousePositionInPage(event) {  
  143.         event = getEvent(event);  
  144.         return {  
  145.             'x':event.pageX || event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft),  
  146.             'y':event.pageY || event.clientY + (document.documentElement.scrollTop || document.body.scrollTop)  
  147.         }  
  148.     }  
  149.  
  150.     window.VVG.getMousePositionInPage = getMousePositionInPage;  
  151.  
  152.     // 停止事件冒泡  
  153.  
  154.     function stopPropagation(event) {  
  155.         if (event.stopPropagation) {  
  156.             event.stopPropagation();  
  157.         } else {  
  158.             event.cancelBubble = true;  
  159.         }  
  160.     }  
  161.  
  162.     window.VVG.stopPropagation = stopPropagation;  
  163.  
  164.     // 阻止默认事件  
  165.  
  166.     function preventDefault(event) {  
  167.         if (event.preventDefault) {  
  168.             event.preventDefault();  
  169.         } else {  
  170.             event.returnValue = false;  
  171.         }  
  172.     }  
  173.  
  174.     window.VVG.preventDefault = preventDefault;  
  175.  
  176.     //  apply从新定义函数的执行环境  
  177.  
  178.     function bindFunction(obj, func) {  
  179.         return function () {  
  180.             return func.apply(obj, arguments);  
  181.         };  
  182.     }  
  183.  
  184.     window.VVG.bindFunction = bindFunction;  
  185.  
  186.     // 设置透明度  
  187.  
  188.     function setOpacity(node, level) {  
  189.         node = $(node);  
  190.         if (document.all) {  
  191.             node.style.filter = 'alpha(opacity=' + level + ')';  
  192.         } else {  
  193.             node.style.opacity = level / 100;  
  194.         }  
  195.     }  
  196.  
  197.     window.VVG.setOpacity = setOpacity;  
  198.  
  199.     // 获取可视窗口尺寸  
  200.  
  201.     function getWindowSize() {  
  202.         var de = document.documentElement;  
  203.         return {  
  204.             'width':(  
  205.                 window.innerWidth || (de && de.clientWidth) || document.body.clientWidth),  
  206.             'height':(  
  207.                 window.innerHeight || (de && de.clientHeight) || document.body.clientHeight)  
  208.         }  
  209.     }  
  210.  
  211.     window.VVG.getWindowSize = getWindowSize;  
  212.  
  213.     //  数字转化为千分位格式函数  
  214.  
  215.     function thousandsNumberFormat(str) {  
  216.         var n = str.length;  
  217.         var c = n % 3;  
  218.         var reg = /\d{3}(?!$)/g;  
  219.         if (n > 3) {  
  220.             var strstr1 = str.slice(0, c);  
  221.             var strstr2 = str.slice(c, n);  
  222.             str1str1 = str1 ? str1 + ',' : '';  
  223.             str = str1 + str2.replace(reg, function (p1) {  
  224.                 return p1 + ',';  
  225.             })  
  226.         }  
  227.         return str;  
  228.     }  
  229.  
  230.     window.VVG.thousandsNumberFormat = thousandsNumberFormat;  
  231.  
  232.     // 带横杠的字符形式转化为驼峰式命名  
  233.  
  234.     function camelize(string) {  
  235.         return string.replace(/-(\w)/g, function (strMatch, p1) {  
  236.             return p1.toUpperCase();  
  237.         });  
  238.     }  
  239.  
  240.     window.VVG.camelize = camelize;  
  241.  
  242.     // 驼峰式转化为横杠分隔  
  243.  
  244.     function uncamelize(string, sep) {  
  245.         sepsep = sep || '-';  
  246.         return string.replace(/([a-z])([A-Z])/g, function (strMatch, p1, p2) {  
  247.             return p1 + sep + p2.toLowerCase();  
  248.         });  
  249.     }  
  250.  
  251.     window.VVG.uncamelize = uncamelize;  
  252.  
  253.     // 设置根据ID设置样式  
  254.  
  255.     function setStyleById(element, cssjson) {  
  256.         element = $(element);  
  257.         for (property in cssjson) {  
  258.             if (!cssjson.hasOwnProperty(property)) continue;  
  259.             if (property == 'opacity') {  
  260.                 setOpacity(element, cssjson[property]);  
  261.             } else {  
  262.                 element.style[camelize(property)] = cssjson[property];  
  263.             }  
  264.         }  
  265.  
  266.     }  
  267.  
  268.     window.VVG.setStyleById = setStyleById;  
  269.     window.VVG.setStyle = setStyleById;  
  270.  
  271.     // 根据Class类设置样式  
  272.  
  273.     function setStyleByClassName(classname, cssjson, parent, tag) {  
  274.         var elements = $$$(classname, parent, tag);  
  275.         for (i = 0n = elements.length; i < n; i++) {  
  276.             setStyleById(elements[i], cssjson);  
  277.         }  
  278.     }  
  279.  
  280.     window.VVG.setStyleByClassName = setStyleByClassName;  
  281.  
  282.     // 根据HTML标签TAG设置样式  
  283.  
  284.     function setStyleByTagName(tag, cssjson, parent) {  
  285.         var tags = $$(tag, parent);  
  286.         for (var i = 0; i < tags.length; i++) {  
  287.             setStyleById(tags[i], cssjson);  
  288.         }  
  289.     }  
  290.  
  291.     window.VVG.setStyleByTagName = setStyleByTagName;  
  292.  
  293.     // 获取Element元素的className  
  294.  
  295.     function getClassNames(element) {  
  296.         if (!(element = $(element))) return false;  
  297.         return element.className.replace(/\s+/g, ' ').split(' ');  
  298.  
  299.  
  300.     }  
  301.  
  302.     window.VVG.getClassNames = getClassNames;  
  303.  
  304.     // 查找element元素是否含有class  
  305.  
  306.     function hasClassName(element, classname) {  
  307.         if (!(element = $(element))) return false;  
  308.         var classNames = getClassNames(element);  
  309.         for (var i = 0; i < classNames.length; i++) {  
  310.             if (classNames[i] === classname) return true;  
  311.         }  
  312.         return false;  
  313.     }  
  314.  
  315.     window.VVG.hasClassName = hasClassName;  
  316.  
  317.     // 增加class  
  318.  
  319.     function addClassName(element, classname) {  
  320.         if (!(element = $(element))) return false;  
  321.         element.className += (element.className ? ' ' : '') + classname;  
  322.     }  
  323.  
  324.     window.VVG.addClassName = addClassName;  
  325.  
  326.     // 删除其中一个className  
  327.  
  328.     function removeClassName(element, classname) {  
  329.         if (!(element = $(element))) return false;  
  330.         if (hasClassName(element, classname)) {  
  331.             var classtexts = getClassNames(element);  
  332.             for (var i = 0; i < classtexts.length; i++) {  
  333.                 if (classtexts[i] == classname) {  
  334.                     delete(classtexts[i]);  
  335.                 }  
  336.             }  
  337.             element.className = classtexts.join(' ');  
  338.         }  
  339.  
  340.     }  
  341.  
  342.     window.VVG.removeClassName = removeClassName;  
  343.  
  344.     // 增加一个外部链接CSS  
  345.  
  346.     function addStyleSheet(url, media) {  
  347.         mediamedia = media || 'screen';  
  348.         var link = document.createElement('LINK');  
  349.         link.setAttribute('rel', 'stylesheet');  
  350.         link.setAttribute('type', 'text/css');  
  351.         link.setAttribute('href', url);  
  352.         link.setAttribute('media', media);  
  353.         document.getElementsByTagName('head')[0].appendChild(link);  
  354.     }  
  355.  
  356.     window.VVG.addStyleSheet = addStyleSheet;  
  357.  
  358.     // 删除一个外部链接CSS  
  359.  
  360.     function removeStyleSheet(url) {  
  361.         var stylesheets = document.getElementsByTagName('link');  
  362.         for (var i = 0; i < stylesheets.length; i++) {  
  363.             if (!(stylesheets[i].href.indexOf(url) == -1)) {  
  364.                 stylesheets[i].parentNode.removeChild(stylesheets[i]);  
  365.                 return true;  
  366.             }  
  367.         }  
  368.         return false;  
  369.     }  
  370.  
  371.     window.VVG.removeStyleSheet = removeStyleSheet;  
  372.  
  373.     // COOKIE 操作  
  374.  
  375.     function getCookie(name) {  
  376.         var start = document.cookie.indexOf(name + "=");  
  377.         var len = start + name.length + 1;  
  378.         if ((!start) && (name != document.cookie.substring(0, name.length))) {  
  379.             return null;  
  380.         }  
  381.         if (start == -1) return null;  
  382.         var end = document.cookie.indexOf(";", len);  
  383.         if (end == -1) end = document.cookie.length;  
  384.         return unescape(document.cookie.substring(len, end));  
  385.     }  
  386.  
  387.     window.VVG.getCookie = getCookie;  
  388.  
  389.     function setCookie(name, value, expires, path, domain, secure) {  
  390.         var today = new Date();  
  391.         today.setTime(today.getTime());  
  392.         if (expires) {  
  393.             expiresexpires = expires * 1000 * 60 * 60 * 24;  
  394.         }  
  395.         var expires_date = new Date(today.getTime() + (expires));  
  396.         document.cookie = name + "=" + escape(value) + ((expires) ? ";expires=" + expires_date.toGMTString() : "") + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : "");  
  397.     }  
  398.  
  399.     window.VVG.setCookie = setCookie;  
  400.  
  401.     function deleteCookie(name, path, domain) {  
  402.         if (getCookie(name)) document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";  
  403.     }  
  404.  
  405.     window.VVG.deleteCookie = deleteCookie;  
  406.  
  407.     // ajax对象操作  
  408.     // 安全过滤JSON的函数parseJSON  
  409.  
  410.     function parseJSON(s, filter) {  
  411.         var j;  
  412.  
  413.         function walk(k, v) {  
  414.             var i;  
  415.             if (v && typeof v === 'object') {  
  416.                 for (i in v) {  
  417.                     if (v.hasOwnProperty(i)) {  
  418.                         v[i] = walk(i, v[i]);  
  419.                     }  
  420.                 }  
  421.             }  
  422.             return filter(k, v);  
  423.         }  
  424.  
  425.         if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(s)) {  
  426.             try {  
  427.                 j = eval('(' + s + ')');  
  428.             } catch (e) {  
  429.                 throw new SyntaxError("parseJSON");  
  430.             }  
  431.         } else {  
  432.             throw new SyntaxError("parseJSON");  
  433.         }  
  434.         if (typeof filter === 'function') {  
  435.             j = walk('', j);  
  436.         }  
  437.         return j;  
  438.     }  
  439.  
  440.     // 创建一个XMLHttpRequest对象  
  441.  
  442.     function getRequestObject(url, options) {  
  443.         var req = false;  
  444.         if (window.XMLHttpRequest) {  
  445.             req = new window.XMLHttpRequest();  
  446.         } else if (window.ActiveXObject) {  
  447.             req = new window.ActiveXObject('Microsoft.XMLHTTP');  
  448.         }  
  449.         if (!req) return false;  
  450.         // 设置默认数据  
  451.         optionsoptions = options || {};  
  452.         optionsoptions.method = options.method || 'GET';  
  453.         optionsoptions.send = options.send || null;  
  454.         // 定义事件侦听函数  
  455.         req.onreadystatechange = function () {  
  456.             switch (req.readyState) {  
  457.                 case 1:  
  458.                     // 正在载入  
  459.                     if (options.loadListener) {  
  460.                         options.loadListener.apply(req, arguments);  
  461.                     }  
  462.                     break;  
  463.                 case 2:  
  464.                     // 载入完成  
  465.                     if (options.loadedListener) {  
  466.                         options.loadedListener.apply(req, arguments);  
  467.                     }  
  468.                     break;  
  469.                 case 3:  
  470.                     // 正在交互  
  471.                     if (options.ineractiveListener) {  
  472.                         options.ineractiveListener.apply(req, arguments);  
  473.                     }  
  474.                     break;  
  475.                 case 4:  
  476.                     // 交互完成  
  477.                     try {  
  478.                         if (req.status && req.status == 200) {  
  479.                             // 获取文件格式  
  480.                             // 为不同的content-type设置对应的方法  
  481.                             var contentType = req.getResponseHeader('Content-Type');  
  482.                             var mimeType = contentType.match(/\s*([^;]+)\s*(;|$)/i)[1];  
  483.                             switch (mimeType) {  
  484.                                 case 'text/plain':  
  485.                                     if (options.txtResponseListener) {  
  486.                                         options.txtResponseListener.call(req, req.responseText);  
  487.                                     }  
  488.                                     break;  
  489.                                 case 'text/javascript':  
  490.                                 case 'application/javascript':  
  491.                                     if (options.jsResponseListener) {  
  492.                                         options.jsResponseListener.call(req, req.responseText);  
  493.                                     }  
  494.                                     break;  
  495.                                 case 'application/json':  
  496.                                     if (options.jsonResponseListener) {  
  497.                                         try {  
  498.                                             var json = parseJSON(req.responseText);  
  499.                                         } catch (e) {  
  500.                                             json = false;  
  501.                                         }  
  502.                                         options.jsonResponseListener.call(req, json);  
  503.                                     }  
  504.                                     break;  
  505.                                 case 'text/xml':  
  506.                                 case 'application/xml':  
  507.                                 case 'application/xhtml+xml':  
  508.                                     if (options.xmlResponseListener) {  
  509.                                         options.xmlResponseListener.call(req, req.responseXML);  
  510.                                     }  
  511.                                     break;  
  512.                                 case 'text/html':  
  513.                                     if (options.htmlResponseListener) {  
  514.                                         options.htmlResponseListener.call(req, req.responseText);  
  515.                                     }  
  516.                                     break;  
  517.                             }  
  518.                             if (options.completeListener) {  
  519.                                 options.completeListener.apply(req, arguments);  
  520.                             }  
  521.                         } else {  
  522.                             if (options.errorListener) {  
  523.                                 options.errorListener.apply(req, arguments);  
  524.                             }  
  525.                         }  
  526.  
  527.                     } catch (e) {  
  528.                         //ignore errors  
  529.                         //alert('Response Error: ' + e);  
  530.                     }  
  531.                     break;  
  532.             }  
  533.         };  
  534.         // Open the request  
  535.         req.open(options.method, url, true);  
  536.         // 添加一个header识别标记  
  537.         req.setRequestHeader('VVG-Base-Ajax-Request', 'AjaxRequest');  
  538.         return req;  
  539.     }  
  540.  
  541.     window.VVG.getRequestObject = getRequestObject;  
  542.  
  543.     // 简易包装send方法与发送XMLHttpRequest请求  
  544.  
  545.     function ajaxRequest(url, options) {  
  546.         var req = getRequestObject(url, options);  
  547.         return req.send(options.send);  
  548.     }  
  549.  
  550.     window.VVG.ajaxRequest = ajaxRequest;  
  551. })(); 

原文链接:http://www.cnblogs.com/NNUF/archive/2012/04/25/2469544.html

【编辑推荐】

  1. JavaScript高级程序设计(第3版)
  2. 面向对象的JavaScript基本知识指南大全
  3. 好用的高质量JavaScript库一览
  4. JavaScript是一门令人愉悦的语言
  5. JavaScript写法你更偏向哪个

 

责任编辑:张伟 来源: VVG的博客
相关推荐

2022-06-16 09:55:58

css轮播图

2015-05-28 10:20:34

js相册翻页

2020-07-10 15:14:28

云计算

2022-04-27 08:00:00

人工智能编程程序员

2022-10-10 08:39:19

CSS前端

2011-04-28 11:33:33

MeeGo平板电脑

2022-09-12 08:31:41

CSS3伪类URI

2012-12-26 09:42:51

2017-01-22 17:25:55

Android放大镜效果源码分析

2023-09-07 07:35:59

JS操作网页

2009-06-08 10:30:22

微软Windows 7操作系统

2009-09-23 10:20:00

2022-10-26 15:54:46

canvas组件鸿蒙

2011-06-03 10:45:09

TransPhoneAndroid平板电脑

2010-12-07 09:30:58

Android 2.3

2012-07-17 09:04:56

Office 15

2010-09-09 12:49:58

鼠标悬停tip效果CSS

2009-08-28 16:03:15

C#程序实现鼠标移动

2012-04-10 14:16:00

腾讯AndroidTita

2018-10-29 10:52:09

海云捷迅AI英特尔
点赞
收藏

51CTO技术栈公众号