JS 常用方法
1. 获取上传文件的后缀名
<input type="file" id="keleyifile" /> <input type="button" value="获取文件后缀名" onclick="Test()" /> <script type="text/javascript"> function GetExtensionFileName(pathfilename){ var reg = /(\\+)/g; var pfn = pathfilename.replace(reg, "#"); var arrpfn = pfn.split("#"); //alert(arrpfn); var fn = arrpfn[arrpfn.length - 1]; var arrfn = fn.split("."); //alert(arrfn); return arrfn[arrfn.length - 1]; } function Test(){ var filePath = "D:\\Program Files\\keleyi\\file.exe"; filePath = document.getElementById("keleyifile").value; if (filePath == ""){ alert("未选择文件"); return; } alert("文件后缀名为:" + GetExtensionFileName(filePath)); } </script>
2. 输入用户名自动显示相关列表
/** * 邮箱自动提示插件 * @constructor EmailAutoComplete * @ options {object} 可配置项 */ function EmailAutoComplete(options) { this.config = { targetCls : '.inputElem', // 目标input元素 parentCls : '.parentCls', // 当前input元素的父级类 hiddenCls : '.hiddenCls', // 当前input隐藏域 searchForm : '.jqtransformdone', //form表单 hoverBg : 'hoverBg', // 鼠标移上去的背景 inputValColor : 'red', // 输入框输入提示颜色 mailArr : ["@qq.com","@qq2.com","@gmail.com","@126.com","@163.com","@hotmail.com","@yahoo.com","@yahoo.com.cn","@live.com","@sohu.com","@sina.com"], //邮箱数组 isSelectHide : true, // 点击下拉框 是否隐藏 默认为true callback : null // 点击某一项回调函数 }; this.cache = { onlyFlag : true, // 只渲染一次 currentIndex : -1, oldIndex : -1 }; this.init(options); } EmailAutoComplete.prototype = { constructor: EmailAutoComplete, init: function(options){ this.config = $.extend(this.config,options || {}); var self = this, _config = self.config, _cache = self.cache; $(_config.targetCls).each(function(index,item){ $(item).keyup(function(e){ var target = e.target, targetVal = $.trim($(this).val()), keycode = e.keyCode, elemHeight = $(this).outerHeight(), elemWidth = $(this).outerWidth(), parentNode = $(this).closest(_config.parentCls); $(parentNode).css({'position':'relative'}); // 如果输入框值为空的话 那么下拉框隐藏 if(targetVal == '') { $(item).attr({'data-html':''}); // 给隐藏域赋值 $(_config.hiddenCls,parentNode).val(''); _cache.currentIndex = -1; _cache.oldIndex = -1; $(".auto-tip",parentNode) && !$(".auto-tip",parentNode).hasClass('hidden') && $(".auto-tip",parentNode).addClass('hidden'); self._removeBg(parentNode); }else { $(item).attr({'data-html':targetVal}); // 给隐藏域赋值 $(_config.hiddenCls,parentNode).val(targetVal); $(".auto-tip",parentNode) && $(".auto-tip",parentNode).hasClass('hidden') && $(".auto-tip",parentNode).removeClass('hidden'); // 渲染下拉框内容 self._renderHTML({keycode:keycode,e:e,target:target,targetVal:targetVal,height:elemHeight,width:elemWidth,parentNode:parentNode}); } }); }); // 阻止form表单默认enter键提交 $(_config.searchForm).each(function(index,item) { $(item).keydown(function(e){ var keyCode = e.keyCode; if(keyCode == 13) { return false; } }); }); // 点击文档document时候 下拉框隐藏掉 $(document).click(function(e){ e.stopPropagation(); var target = e.target, tagCls = _config.targetCls.replace(/^\./,''); if(!$(target).hasClass(tagCls)) { $('.auto-tip') && $('.auto-tip').each(function(index,item){ !$(item).hasClass('hidden') && $(item).addClass('hidden'); }); } }); }, /* * 渲染下拉框提示内容 * @param cfg{object} */ _renderHTML: function(cfg) { var self = this, _config = self.config, _cache = self.cache, curVal; var curIndex = self._keyCode(cfg.keycode); $('.auto-tip',cfg.parentNode).hasClass('hidden') && $('.auto-tip',cfg.parentNode).removeClass('hidden'); if(curIndex > -1){ // 键盘上下操作 self._keyUpAndDown(cfg.targetVal,cfg.e,cfg.parentNode); }else { if(/@/.test(cfg.targetVal)) { curVal = cfg.targetVal.replace(/@.*/,''); }else { curVal = cfg.targetVal; } if(_cache.onlyFlag) { $(cfg.parentNode).append('<input type="hidden" class="hiddenCls"/>'); var wrap = '<ul class="auto-tip">'; for(var i = 0; i < _config.mailArr.length; i++) { wrap += '<li class="p-index'+i+'">'+'<span class="output-num"></span><em class="em" data-html="'+_config.mailArr[i]+'">'+_config.mailArr[i]+'</em></li>'; } wrap += '</ul>'; _cache.onlyFlag = false; $(cfg.parentNode).append(wrap); $('.auto-tip',cfg.parentNode).css({'position':'absolute','top':cfg.height,'width':cfg.width - 2 + 'px','left':0, 'border':'1px solid #ccc','z-index':10000}); } // 给所有li添加属性 data-html $('.auto-tip li',cfg.parentNode).each(function(index,item){ $('.output-num',item).html(curVal); !$('.output-num',item).hasClass(_config.inputValColor) && $('.output-num',item).addClass(_config.inputValColor); var emVal = $.trim($('.em',item).attr('data-html')); $(item).attr({'data-html':curVal + '' +emVal}); }); // 精确匹配内容 self._accurateMate({target:cfg.target,parentNode:cfg.parentNode}); // 鼠标移到某一项li上面时候 self._itemHover(cfg.parentNode); // 点击对应的项时 self._executeClick(cfg.parentNode); } }, /** * 精确匹配某项内容 */ _accurateMate: function(cfg) { var self = this, _config = self.config, _cache = self.cache; var curVal = $.trim($(cfg.target,cfg.parentNode).attr('data-html')), newArrs = []; if(/@/.test(curVal)) { // 获得@ 前面 后面的值 var prefix = curVal.replace(/@.*/, ""), suffix = curVal.replace(/.*@/, ""); $.map(_config.mailArr,function(n){ var reg = new RegExp(suffix); if(reg.test(n)) { newArrs.push(n); } }); if(newArrs.length > 0) { $('.auto-tip',cfg.parentNode).html(''); $(".auto-tip",cfg.parentNode) && $(".auto-tip",cfg.parentNode).hasClass('hidden') && $(".auto-tip",cfg.parentNode).removeClass('hidden'); var html = ''; for(var j = 0, jlen = newArrs.length; j < jlen; j++) { html += '<li class="p-index'+j+'">'+'<span class="output-num"></span><em class="em" data-html="'+newArrs[j]+'">'+newArrs[j]+'</em></li>'; } $('.auto-tip',cfg.parentNode).html(html); // 给所有li添加属性 data-html $('.auto-tip li',cfg.parentNode).each(function(index,item){ $('.output-num',item).html(prefix); !$('.output-num',item).hasClass(_config.inputValColor) && $('.output-num',item).addClass(_config.inputValColor); var emVal = $.trim($('.em',item).attr('data-html')); $(item).attr('data-html',''); $(item).attr({'data-html':prefix + '' +emVal}); }); // 精确匹配到某项时候 让当前的索引等于初始值 _cache.currentIndex = -1; _cache.oldIndex = -1; $('.auto-tip .output-num',cfg.parentNode).html(prefix); // 鼠标移到某一项li上面时候 self._itemHover(cfg.parentNode); // 点击对应的项时 self._executeClick(cfg.parentNode); }else { $(".auto-tip",cfg.parentNode) && !$(".auto-tip",cfg.parentNode).hasClass('hidden') && $(".auto-tip",cfg.parentNode).addClass('hidden'); $('.auto-tip',cfg.parentNode).html(''); } } }, /* * 鼠标移到某一项li上时 */ _itemHover: function(parentNode) { var self = this, _config = self.config, _cache = self.cache; $('.auto-tip li',parentNode).hover(function(index,item) { !$(this).hasClass(_config.hoverBg) && $(this).addClass(_config.hoverBg); },function() { $(this).hasClass(_config.hoverBg) && $(this).removeClass(_config.hoverBg); }); }, /* * 当输入框值为空时候 li项都删掉class hoverBg */ _removeBg: function(parentNode){ var self = this, _config = self.config; $(".auto-tip li",parentNode).each(function(index,item){ $(item).hasClass(_config.hoverBg) && $(item).removeClass(_config.hoverBg); }); }, /** * 键盘上下键操作 */ _keyUpAndDown: function(targetVal,e,parentNode) { var self = this, _cache = self.cache, _config = self.config; // 如果请求成功后 返回了数据(根据元素的长度来判断) 执行以下操作 if($('.auto-tip' + ' li',parentNode) && $('.auto-tip' + ' li').length > 0) { var plen = $('.auto-tip' + ' li',parentNode).length, keyCode = e.keyCode; _cache.oldIndex = _cache.currentIndex; // 上移操作 if(keyCode == 38) { if(_cache.currentIndex == -1) { _cache.currentIndex = plen - 1; }else { _cache.currentIndex = _cache.currentIndex - 1; if(_cache.currentIndex < 0) { _cache.currentIndex = plen - 1; } } if(_cache.currentIndex !== -1) { !$('.auto-tip .p-index'+_cache.currentIndex,parentNode).hasClass(_config.hoverBg) && $('.auto-tip .p-index'+_cache.currentIndex,parentNode).addClass(_config.hoverBg).siblings().removeClass(_config.hoverBg); var curAttr = $('.auto-tip' + ' .p-index'+_cache.currentIndex,parentNode).attr('data-html'); $(_config.targetCls,parentNode).val(curAttr); // 给隐藏域赋值 $(_config.hiddenCls,parentNode).val(curAttr); } }else if(keyCode == 40) { //下移操作 if(_cache.currentIndex == plen - 1) { _cache.currentIndex = 0; }else { _cache.currentIndex++; if(_cache.currentIndex > plen - 1) { _cache.currentIndex = 0; } } if(_cache.currentIndex !== -1) { !$('.auto-tip .p-index'+_cache.currentIndex,parentNode).hasClass(_config.hoverBg) && $('.auto-tip .p-index'+_cache.currentIndex,parentNode).addClass(_config.hoverBg).siblings().removeClass(_config.hoverBg); var curAttr = $('.auto-tip' + ' .p-index'+_cache.currentIndex,parentNode).attr('data-html'); $(_config.targetCls,parentNode).val(curAttr); // 给隐藏域赋值 $(_config.hiddenCls,parentNode).val(curAttr); } }else if(keyCode == 13) { //回车操作 var curVal = $('.auto-tip' + ' .p-index'+_cache.oldIndex,parentNode).attr('data-html'); $(_config.targetCls,parentNode).val(curVal); // 给隐藏域赋值 $(_config.hiddenCls,parentNode).val(curVal); if(_config.isSelectHide) { !$(".auto-tip",parentNode).hasClass('hidden') && $(".auto-tip",parentNode).addClass('hidden'); } _config.callback && $.isFunction(_config.callback) && _config.callback(); _cache.currentIndex = -1; _cache.oldIndex = -1; } } }, _keyCode: function(code) { var arrs = ['17','18','38','40','37','39','33','34','35','46','36','13','45','44','145','19','20','9']; for(var i = 0, ilen = arrs.length; i < ilen; i++) { if(code == arrs[i]) { return i; } } return -1; }, /** * 当数据相同的时 点击对应的项时 返回数据 */ _executeClick: function(parentNode) { var _self = this, _config = _self.config; $('.auto-tip' + ' li',parentNode).unbind('click'); $('.auto-tip' + ' li',parentNode).bind('click',function(e){ var dataAttr = $(this).attr('data-html'); $(_config.targetCls,parentNode).val(dataAttr); if(_config.isSelectHide) { !$(".auto-tip",parentNode).hasClass('hidden') && $(".auto-tip",parentNode).addClass('hidden'); } // 给隐藏域赋值 $(_config.hiddenCls,parentNode).val(dataAttr); _config.callback && $.isFunction(_config.callback) && _config.callback(); }); } }; // 初始化 $(function() { new EmailAutoComplete({}); });
3. 生成0-9的随机数
function random(min,max){ return Math.floor(min+Math.random()*(max-min)); } random(0,9);
4. 全屏漂浮广告、移入光标停止移动
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JS全屏漂浮广告-柯乐义</title> <style type="text/css"> div#roll{width:100px;height:100px; background-color:#000; color:#fff; position:absolute;} </style> </head> <body> <div> <div><h2>JS全屏漂浮广告,移入光标停止移动·柯乐义</h2><a href="http://keleyi.com/a/bjac/ara6jk5h.htm" target="_blank">原文</a></div> </div> <div id="roll">我是广告<br />keleyi.com</div> <script type="text/javascript"> var ggRoll = { roll: document.getElementById("roll"), speed: 20, statusX: 1, statusY: 1, x: 100, y: 300, winW: document.documentElement.clientWidth - document.getElementById("roll").offsetWidth, winH: document.documentElement.clientHeight - document.getElementById("roll").offsetHeight, Go: function () { this.roll.style.left = this.x + 'px'; this.roll.style.top = this.y + 'px'; this.x = this.x + (this.statusX ? -1 : 1) if (this.x < 0) { this.statusX = 0 } if (this.x > this.winW) { this.statusX = 1 } this.y = this.y + (this.statusY ? -1 : 1) if (this.y < 0) { this.statusY = 0 } if (this.y > this.winH) { this.statusY = 1 } } } var interval = setInterval("ggRoll.Go()", ggRoll.speed); ggRoll.roll.onmouseover = function () { clearInterval(interval) }; ggRoll.roll.onmouseout = function () { interval = setInterval("ggRoll.Go()", ggRoll.speed) }; </script> </body> </html>
5. 整数金额大写转换方法
function digit_uppercase(n) { var digit = [ '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' ]; var unit = [ ['元', '万', '亿'], ['', '拾', '佰', '仟'] ]; var s = ''; for (var i = 0; i < unit[0].length && n > 0; i++) { var p = ''; for (var j = 0; j < unit[1].length && n > 0; j++) { p = digit[n % 10] + unit[1][j] + p; n = Math.floor(n / 10); } s = p.replace(/(零.)*零$/, '') .replace(/^$/, '零') + unit[0][i] + s; } return s.replace(/(零.)*零元/, '元') .replace(/(零.)+/g, '零') .replace(/^$/, '零元') + '整'; } 测试代码: alert(digit_uppercase(0)); // 零元整 alert(digit_uppercase(123)); // 壹佰贰拾叁元整 alert(digit_uppercase(1000000)); // 壹佰万元整 alert(digit_uppercase(100000001)); // 壹亿零壹元整 alert(digit_uppercase(1000000000)); // 壹拾亿元整 alert(digit_uppercase(1234567890)); // 壹拾贰亿叁仟肆佰伍拾陆万柒仟捌佰玖拾元整 alert(digit_uppercase(1001100101)); // 壹拾亿零壹佰壹拾万零壹佰零壹元整 alert(digit_uppercase(110101010)); // 壹亿壹仟零壹拾万壹仟零壹拾元整
6. 随机抽奖
<html> <title>随机抽奖程序</title> <head><meta http-equiv=Content-Type content="text/html; charset=gb2312"> </head> <body> <script type="text/javascript"> var alldata = "a,b,c,d,e" var alldataarr = alldata.split(","); var num = alldataarr.length-1 ; var timer function change() { document.getElementById("oknum").innerHTML = alldataarr[GetRnd(0,num)]; } function start(){ clearInterval(timer); timer = setInterval('change()',10); } function ok(){ clearInterval(timer); document.getElementById("showresult").value=document.getElementById("oknum").innerText; } function GetRnd(min,max){ return parseInt(Math.random()*(max-min+1)); } </script> <center> <div id="oknum" name="oknum" >请单击开始</div> <button onclick="start()" accesskey="s">开始</button> <button onclick="ok()" accesskey="o">停止</button> 您的选择是: <input type="text" id="showresult" value=""> </center> </body> </html>
7. 图片轮播 原生JS
<style> body{ font-family:"Times New Roman", Times, serif;} /* 柯乐义 2013 http://keleyi.com */ #box-keleyi-com li,ul,p { margin: 0; padding: 0; } #box-keleyi-com ul{ list-style-type:none; } #box-keleyi-com { position:relative; width:492px; height:172px; margin:10px auto; } #box-keleyi-com .imgList{ position:relative; width:490px; height:170px; overflow:hidden; } #box-keleyi-com .imgList li{ position:absolute; top:0; left:0; width:490px; height:170px; } #box-keleyi-com .countNum{ position:absolute; right:0; bottom:5px; } #box-keleyi-com .countNum li{ width:20px; height:20px; float:left; color:#fff; border-radius:20px; background:#f90; text-align:center; margin-right:5px; cursor:pointer; opacity:0.7; filter:alpha(opacity=70); } #box-keleyi-com .countNum li.current{ background:#f60; font-weight:bold; opacity:1; filter:alpha(opacity=70); } </style> <body> <div style="width:500px;margin:0px auto;"><h2>原生javascript图片轮播</h2> <a href="http://keleyi.com/a/bjac/9jsb6j23.htm" target="_blank">原文</a> </div> <div id="box-keleyi-com"></div> </body> <script> function runImg() { } runImg.prototype = { bigbox: null, //最外层容器 boxul: null, //子容器ul imglist: null, //子容器img numlist: null, //子容器countNum prov: 0, //上次显示项 index: 0, //当前显示项 timer: null, //控制图片转变效果 play: null, //控制自动播放 imgurl: [], //存放图片 count: 0, //存放的个数 $: function (obj) { if (typeof (obj) == "string") { if (obj.indexOf("#") >= 0) { obj = obj.replace("#", ""); if (document.getElementById(obj)) { return document.getElementById(obj); } else { alert("柯乐义提示:没有容器" + obj); return null; } } else { return document.createElement(obj); } } else { return obj; } }, //初始化 info: function (id) { this.count = this.count <= 5 ? this.count : 5; this.bigbox = this.$(id); for (var i = 0; i < 2; i++) { var ul = this.$("ul"); for (var j = 1; j <= this.count; j++) { var li = this.$("li"); li.innerHTML = i == 0 ? this.imgurl[j - 1] : j; ul.appendChild(li); } this.bigbox.appendChild(ul); } this.boxul = this.bigbox.getElementsByTagName("ul"); this.boxul[0].className = "imgList"; this.boxul[1].className = "countNum"; this.imglist = this.boxul[0].getElementsByTagName("li"); this.numlist = this.boxul[1].getElementsByTagName("li"); for (var j = 0; j < this.imglist.length; j++) { this.alpha(j, 0); } this.alpha(0, 100); this.numlist[0].className = "current"; }, //封装程序入口 action: function (id) { this.autoplay(); this.mouseoverout(this.bigbox, this.numlist); }, //图片切换效果 imgshow: function (num, numlist, imglist) { this.index = num; var pralpha = 100; var inalpha = 0; for (var i = 0; i < numlist.length; i++) { numlist[i].className = ""; } numlist[this.index].className = "current"; clearInterval(this.timer); for (var j = 0; j < this.imglist.length; j++) { this.alpha(j, 0); } this.alpha(this.prov, 100); this.alpha(this.index, 0); var $this = this; //利用透明度来实现切换图片 this.timer = setInterval(function () { inalpha += 2; pralpha -= 2; if (inalpha > 100) { inalpha = 100 }; //不能大于100 if (pralpha < 0) { pralpha = 100 }; //为兼容性赋样式 $this.alpha($this.prov, pralpha); $this.alpha($this.index, inalpha); if (inalpha == 100 && pralpha == 0) { clearInterval($this.timer) }; //当等于100的时候就切换完成了 }, 20)//经测试20是我认为最合适的值 }, //设置透明度 alpha: function (i, opacity) { this.imglist[i].style.opacity = opacity / 100; this.imglist[i].style.filter = "alpha(opacity=" + opacity + ")"; }, //自动播放 autoplay: function () { var $this = this; this.play = setInterval(function () { $this.prov = $this.index; $this.index++; if ($this.index > $this.imglist.length - 1) { $this.index = 0 }; $this.imgshow($this.index, $this.numlist, $this.imglist); }, 2000) }, //处理鼠标事件 mouseoverout: function (box, numlist) { var $this = this; box.onmouseover = function () { clearInterval($this.play); } box.onmouseout = function () { $this.autoplay($this.index); } for (var i = 0; i < numlist.length; i++) { numlist[i].index = i; numlist[i].onmouseover = function () { $this.prov = $this.index; $this.imgshow(this.index, $this.numlist, $this.imglist); } } } } </script>
轮播汇总 http://keleyi.com/a/bjac/s3sw6q5t.htm
8. 判断是IE几浏览器
var isIE=!!window.ActiveXObject; var isIE6=isIE&&!window.XMLHttpRequest; var isIE8=isIE&&!!document.documentMode; var isIE7=isIE&&!isIE6&&!isIE8; if (isIE){ if (isIE6){ alert(”ie6〃); }else if (isIE8){ alert(”ie8〃); }else if (isIE7){ alert(”ie7〃); } }
9. 横条广告带上下滚动
<!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 name="keywords" content="JS代码,焦点图,JS广告代码,JS特效代码" /> <meta name="description" content="此代码内容为可调节尺寸的banner广告条效果,属于站长常用代码,更多焦点图代码请访问柯乐义JS代码频道。" /> <title>横条广告带上下滚动_柯乐义</title><base target="_blank" /> </head> <body style="text-align:center"> <h2>横条广告带上下滚动</h2> <div id="ad_headerbanner"><SCRIPT src="http://keleyi.com/keleyi/phtml/flash/js/keleyi.falsh.js" type=text/javascript></SCRIPT> <SCRIPT type=text/javascript> <!-- var fp_pics="",fp_links=""; //广告图片与链接 fp_pics += "§"+"http://keleyi.com/keleyi/phtml/flash/images/w1.jpg"; //广告图片地址 fp_links += "§"+escape("http://keleyi.com/a/bjac/3wjq3xm2.htm"); //广告链接地址 //广告图片与链接 fp_pics += "§"+"http://keleyi.com/keleyi/phtml/flash/images/w2.jpg"; //广告图片地址 fp_links += "§"+escape("http://keleyi.com/a/bjac/06r1x7tg.htm"); //广告链接地址 //广告图片与链接 fp_pics += "§"+"http://keleyi.com/keleyi/phtml/flash/images/w3.jpg"; //广告图片地址 fp_links += "§"+escape("http://keleyi.com/a/bjac/gucmqug3.htm"); //广告链接地址 fp_pics=fp_pics.substring(1); fp_links=fp_links.substring(1); //默认图片与链接 var def_pic = "images/w2.jpg"; //默认图片地址 var def_link = escape("http://keleyi.com/"); //默认图片链接 var FP = new zadaiFlash("http://keleyi.com/keleyi/phtml/flash/flipper.swf", "FP_L_swf", 950, 90, "7", "#FFFFFF", false, "High"); FP.addParam("menu", "false"); FP.addParam("wmode", "transparent"); FP.addVariable("pic_width", "950"); //图片宽 FP.addVariable("pic_height", "90"); //图片高 FP.addVariable("flip_time", "300"); //翻牌速度 FP.addVariable("pause_time", "2000"); //间隔时间 FP.addVariable("wait_time", "2000"); //等待时间 FP.addVariable("pics", fp_pics); //广告图片地址 FP.addVariable("urls", fp_links); //广告链接地址 FP.addVariable("def_pic", def_pic); //默认图片地址 FP.addVariable("def_link", def_link); //默认链接地址 FP.write("ad_headerbanner"); //--> </SCRIPT></div> <br><br> <p><a href="http://keleyi.com/a/bjac/8qx83gls.htm">原文</a> 代码整理:<a href="http://keleyi.com/" target="_blank">柯乐义</a></p> </body> </html>
10. 烟花效果
<!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" /> <title>JavaScript烟花效果-柯乐义</title> <script type="text/javascript"> /* http://keleyi.com */ var yanhua = "yanhua.keleyi.com"; var fireworks = function () { this.size = 20; this.rise(); } fireworks.prototype = { color: function () { var c = ['0', '3', '6', '9', 'c', 'f']; var t = [c[Math.floor(Math.random() * 100) % 6], '0', 'f']; if (yanhua === 'yanhua.ke' + 'leyi.' + 'com') t.sort(function () { return Math.random() > 0.5 ? -1 : 1; }); return '#' + t.join(''); }, aheight: function () { var h = document.documentElement.clientHeight - 250; return Math.abs(Math.floor(Math.random() * h - 200)) + 201; }, firecracker: function () { var b = document.createElement('div'); var w = document.documentElement.clientWidth; b.style.position = 'absolute'; b.style.color = this.color(); b.style.bottom = 0; b.style.left = Math.floor(Math.random() * w) + 1 + 'px'; document.body.appendChild(b); return b; }, rise: function () { var o = this.firecracker(); var n = this.aheight(); var c = this.color; var e = this.expl; var s = this.size; var k = n; var m = function () { o.style.bottom = parseFloat(o.style.bottom) + k * 0.1 + 'px'; k -= k * 0.1; if (k < 2) { clearInterval(clear); e(o, n, s, c); } } o.innerHTML = '.'; if (parseInt(o.style.bottom) < n) { var clear = setInterval(m, 20); } }, expl: function (o, n, s, c) { var R = n / 3, Ri = n / 6, Rii = n / 9; var r = 0, ri = 0, rii = 0; if (yanhua === 'yanhua.ke' + 'leyi.' + 'com') for (var i = 0; i < s; i++) { var span = document.createElement('span'); var p = document.createElement('i'); var a = document.createElement('a'); span.style.position = 'absolute'; span.style.fontSize = n / 10 + 'px'; span.style.left = 0; span.style.top = 0; span.innerHTML = '*'; p.style.position = 'absolute'; p.style.left = 0; p.style.top = 0; p.innerHTML = '*'; a.style.position = 'absolute'; a.style.left = 0; a.style.top = 0; a.innerHTML = '*'; o.appendChild(span); o.appendChild(p); o.appendChild(a); } function spr() { r += R * 0.1; ri += Ri * 0.06; rii += Rii * 0.06; sp = o.getElementsByTagName('span'); p = o.getElementsByTagName('i'); a = o.getElementsByTagName('a'); for (var i = 0; i < sp.length; i++) { sp[i].style.color = c(); p[i].style.color = c(); a[i].style.color = c(); sp[i].style.left = r * Math.cos(360 / s * i) + 'px'; sp[i].style.top = r * Math.sin(360 / s * i) + 'px'; sp[i].style.fontSize = parseFloat(sp[i].style.fontSize) * 0.96 + 'px'; p[i].style.left = ri * Math.cos(360 / s * i) + 'px'; p[i].style.top = ri * Math.sin(360 / s * i) + 'px'; p[i].style.fontSize = parseFloat(sp[i].style.fontSize) * 0.96 + 'px'; a[i].style.left = rii * Math.cos(360 / s * i) + 'px'; a[i].style.top = rii * Math.sin(360 / s * i) + 'px'; a[i].style.fontSize = parseFloat(sp[i].style.fontSize) * 0.96 + 'px'; } R -= R * 0.1; if (R < 2) { o.innerHTML = ''; o.parentNode.removeChild(o); clearInterval(clearI); } }if(yanhua==='yanhua.ke'+'leyi.'+'com') var clearI = setInterval(spr, 20); } } window.onload = function () { function happyNewYear_keleyi_com() { new fireworks(); } if (yanhua === 'yanhua.ke' + 'le'+'yi.' + 'com') setInterval(happyNewYear_keleyi_com, 1000); } </script> <style type="text/css"> </style> </head> <body style="background:#000;font:12px Georgia, 'Times New Roman', Times, serif"> <div style="color:red;height:140px;width:800px;margin:0px auto;"><h2>节日的烟花·柯乐义</h2><a href="http://keleyi.com/a/bjac/pq9s82yy.htm" target="_blank">原文</a></div> </body> </html>
<!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" /> <title>JavaScript烟花效果(二)-柯乐义</title> <script type="text/javascript"> /* http://keleyi.com */ var yanhua = "yanhua.keleyi.com"; var firework = function () { this.size = 40; this.speed = 0.1; this.rise(); } firework.prototype = { color: function () { var c = ['0', '3', '6', '9', 'c', 'f']; var t = [c[Math.floor(Math.random() * 100) % 6], '0', 'f']; t.sort(function () { return Math.random() > 0.5 ? -1 : 1; }); return '#' + t.join(''); }, aheight: function () { var h = document.documentElement.clientHeight; return Math.abs(Math.floor(Math.random() * h - 200)) + 201; }, firecracker: function () { var b = document.createElement('div'); var w = document.body.clientWidth; b.style.color = this.color(); b.style.position = 'absolute'; b.style.bottom = 0; b.style.left = Math.floor(Math.random() * w) + 1 + 'px'; document.body.appendChild(b); return b; }, rise: function () { var o = this.firecracker(); var n = this.aheight(); var speed = this.speed; var e = this.expl; var s = this.size; var k = n; var m = function () { o.style.bottom = parseFloat(o.style.bottom) + k * speed + 'px'; k -= k * speed; if (k < 2) { clearInterval(clear); e(o, n, s, speed); } } o.innerHTML = '*'; if (parseInt(o.style.bottom) < n) { var clear = setInterval(m, 20); } }, expl: function (o, n, s, speed) { var R = n / 3; var Ri = n / 6; var r = 0; var ri = 0; for (var i = 0; i < s; i++) { var span = document.createElement('span'); var p = document.createElement('p'); span.style.position = 'absolute'; span.style.left = 0; span.style.top = 0; span.innerHTML = '*'; p.style.position = 'absolute'; p.style.left = 0; p.style.top = 0; p.innerHTML = '+'; o.appendChild(span); o.appendChild(p); } function spr() { r += R * speed; ri += Ri * speed / 2; sp = o.getElementsByTagName('span'); p = o.getElementsByTagName('p'); for (var i = 0; i < sp.length; i++) { sp[i].style.left = r * Math.cos(360 / s * i) + 'px'; sp[i].style.top = r * Math.sin(360 / s * i) + 'px'; p[i].style.left = ri * Math.cos(360 / s * i) + 'px'; p[i].style.top = ri * Math.sin(360 / s * i) + 'px'; } R -= R * speed; if (R < 2) { clearInterval(clearI); o.parentNode.removeChild(o); } } var clearI = setInterval(spr, 20); } } window.onload = function () { function happyNewYear() { new firework(); } if (yanhua === 'yanhua.ke' + 'leyi.' + 'com') setInterval(happyNewYear, 400); } </script> </head> <body style="background:#000;font:12px Georgia, 'Times New Roman', Times, serif"> <div style="color:red;height:140px;width:800px;margin:0px auto;"><h2>节日的烟花(二)·柯乐义</h2><div><script type="text/javascript" src="/kineryi/js/gggg728x90a.js"></script><a href="http://keleyi.com/a/bjac/e45ghtrx.htm" target="_blank">原文</a></div></div> </body> </html>
<!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> <title>Javascript多彩雪花从天降-柯乐义</title> <style type="text/css"> .KeleyiSnow{display:block; overflow:hidden; font-size:12px; position:absolute}; body{background:#000;margin:0px} html{overflow:hidden; background:#000;} a{color:White;text-decoration:none} .keleyiTitle{color:red;height:140px;width:800px;margin:0px auto;text-align:center} </style> </head> <body> <script type="text/javascript"> /* http://keleyi.com */ var yanhua = "yanhua.keleyi.com"; var Fire = function (r, color) { this.radius = r || 12; this.color = color || "FF6600"; this.xpos = 0; this.ypos = 0; this.zpos = 0; this.vx = 0; this.vy = 0; this.vz = 0; this.mass = 1; this.p = document.createElement("span"); this.p.className = "Ke"+"leyiSnow"; this.p.innerHTML = "*"; this.p.style.fontSize = this.radius + "px"; this.p.style.color = "#" + this.color; } Fire.prototype = { append: function (parent) { parent.appendChild(this.p); }, setSize: function (scale) { this.p.style.fontSize = this.radius * scale + "px"; }, setPosition: function (x, y) { this.p.style.left = x + "px"; this.p.style.top = y + "px"; }, setVisible: function (b) { this.p.style.display = b ? "block" : "none"; } } var fireworks = function () { var fires = new Array(); var count = 100; var fl = 250; var vpx = 500; var vpy = 300; var gravity = .3; var floor = 200; var bounce = -.8; var timer; return { init: function () { for (var i = 0; i < count; i++) { var color = 0xFF0000; color = (Math.random() * 0xFFFFFF).toString(16).toString().split(".")[0]; while (color.length < 6) { color = "0" + color; } var fire = new Fire(12, color); fires.push(fire); fire.ypos = -100; fire.vx = Math.random() * 6 - 3; fire.vy = Math.random() * 6 - 3; fire.vz = Math.random() * 6 - 3; fire.append(document.body); } var that = this; timer = setInterval(function () { for (var i = 0; i < count; i++) { that.move(fires[i]); } }, 30); }, move: function (fire) { fire.vy += gravity; fire.xpos += fire.vx; fire.ypos += fire.vy; fire.zpos += fire.vz; if (fire.ypos > floor) { fire.ypos = floor; fire.vy *= bounce; } if (fire.zpos > -fl) { var scale = fl / (fl + fire.zpos); fire.setSize(scale); fire.setPosition(vpx + fire.xpos * scale, vpy + fire.ypos * scale); fire.setVisible(true); } else { fire.setVisible(false); } } } } if (yanhua === 'yanhua.ke' + 'leyi.' + 'com') fireworks().init(); function KeleyiSnow() { window.location.reload(); } if (yanhua === 'yanhua.ke' + 'leyi.' + 'com') setInterval(KeleyiSnow, 6000); </script> <div class="keleyiTitle"><h2>多彩雪花从天降·柯乐义</h2><a href="http://keleyi.com/a/bjac/flyuqb6r.htm" target="_blank">原文</a> 请最大化窗口查看</div> </body> </html>
11. 确认关闭网页
<!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>
<title>关闭网页确认-柯乐义</title><base target="_blank" />
</head>
<body onbeforeunload="return '确定关闭页面吗?';">
<div>
当您关闭页面时,会弹出对话框,让您确认是否离开页面,选择确定则页面关闭,否则页面不关闭。
</div>
<dl>
<dt><a href="http://keleyi.com/a/bjac/nmixur5x.htm">原文</a></dt>
<dt><a href="http://keleyi.com/a/bjac/4me5brln.htm">Javascript的变量作用域原理详解</a></dt>
<dt><a href="http://keleyi.com/a/bjac/dyloru9f.htm">js获取屏幕分辨率</a></dt>
<dt><a href="http://keleyi.com/a/bjac/958fkivi.htm" title="JS的encodeURI和encodeURIComponent的区别">JS的encodeURI和encodeURIComponent...</a></dt>
<dt><a href="http://keleyi.com/a/bjac/4esxhwgr.htm">js存、取、删除cookies实例</a></dt>
<dt><a href="http://keleyi.com/a/bjac/vdjhuxl9.htm">javascript正则表达式基础入门与进阶</a></dt>
<dt><a href="http://keleyi.com/a/bjac/ovyge49k.htm">js获取页面中图片的总数</a></dt>
<dt><a href="http://keleyi.com/a/bjac/o315ujff.htm">HTML DOM Document 对象概述</a></dt>
<dt><a href="http://keleyi.com/a/bjac/j67kkxas.htm">匹配HTML标记的jScript正则表达式</a></dt>
<dt><a href="http://keleyi.com/a/bjac/xow8pdfd.htm">JavaScript访问JSON数据</a></dt>
<dt><a href="http://keleyi.com/a/bjac/b18qrru8.htm" title="js改进window.onload方法document.ready">js改进window.onload方法document.re...</a></dt>
</dl>
<div><input onclick="javascript:window.opener=null;window.open('','_self');window.close();" type="button" value="关闭页面"/></div>
</body>
</html>
12. AJAX实例
<div id="ajax_keleyi_com"></div> <input type="button" value="Ajax获取内容" onclick="startAjaxRequest()" /> <script> var xmlHttp; function createXMLHttpRequest(){ if (window.ActiveXObject){ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest){ xmlHttp = new XMLHttpRequest(); } } function startAjaxRequest(){ var host='http://keleyi.com/zliao/g/content/g1.htm'; createXMLHttpRequest(); xmlHttp.open('GET', host, true); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.send(''); } function handleStateChange(){ if(xmlHttp.readyState == 4){ if(xmlHttp.status == 200){ var keleyi_g1 = xmlHttp.responseText; document.getElementById("ajax_keleyi_com").innerHTML=keleyi_g1; } } } </script>
13. 获取IP地址
<div id="keleyivisitorip"></div> <script> window.onload = function () { document.getElementById("keleyivisitorip").innerHTML="125.46.77.2" } </script>
14. 点击按钮后变灰,并倒计时
<input type="button" id="btn" value="免费获取验证码" /> <script type="text/javascript"> var wait=60; function time(o) { if (wait == 0) { o.removeAttribute("disabled"); o.value="免费获取验证码"; wait = 60; } else { o.setAttribute("disabled", true); o.value=wait+"秒后可以重新发送"; wait--; setTimeout(function() { time(o) }, 1000) } } document.getElementById("btn").onclick=function(){time(this);} </script>
15. js复制到粘贴板,支持IE、Chrome、火狐等多种浏览器
<html> <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>复制页面内容到粘贴板,支持IE、Chrome、火狐等多种浏览器-柯乐义</title> <style type="text/css"> body { font-family:arial,sans-serif; font-size:9pt; } .my_clip_button { width:150px; text-align:center; border:1px solid black; background-color:#ccc; margin:10px; padding:10px; cursor:default; font-size:9pt; } .my_clip_button.hover { background-color:#eee; } .my_clip_button.active { background-color:#aaa; } </style> <script type="text/javascript" src="http://keleyi.com/keleyi/phtml/liulanqi/index/KeleyiClipboard.js"></script> <script type="text/javascript"> var clip = null; function $(id) { return document.getElementById(id); } function init() { clip = new ZeroClipboard.Client(); clip.setHandCursor(true); clip.addEventListener('load', function (client) { debugstr("准备就绪"); }); clip.addEventListener('mouseOver', function (client) { // update the text on mouse over clip.setText($('fe_text').value); }); clip.addEventListener('complete', function (client, text) { debugstr("已经把这些文本复制到粘贴板: " + text); }); clip.glue('d_clip_button', 'd_clip_container'); } function debugstr(msg) { var p = document.createElement('p'); p.innerHTML = msg; $('d_debug').appendChild(p); } </script> </head> <body onLoad="init()"> <h1>复制页面内容到粘贴板</h1> <p><script> document.write("您的浏览器是: " + navigator.userAgent);</script></p> <table width="100%"> <tr> <td width="50%" valign="top"> <!-- Upload Form --> <table> <tr> <td align="right"><b>文本:</b></td> <td align="left"><textarea id="fe_text" cols=50 rows=5 onChange="clip.setText(this.value)">柯乐义文本复制,点击下面的按钮,将会把这里的文本复制到粘贴板。http://keleyi.com 还可以改变这里的文本试试。</textarea></td> </tr> </table> <br/> <div id="d_clip_container" style="position:relative"> <div id="d_clip_button" class="my_clip_button"><b>复制到粘贴板</b></div> </div> </td> <td width="50%" valign="top"> <!-- Debug Console --> <div id="d_debug" style="border:1px solid #aaa; padding: 10px; font-size:9pt;"> <h3>状态和已经复制的内容:</h3> </div> </td> </tr> </table> <br/><br/> 在这里粘贴,看看是不是已经复制了上面内容<br/> <textarea id="testarea" cols=50 rows=10></textarea><br/> <input type=button value="清空" onClick="$('testarea').value = '';"/> </body> </html>
16. 当前页面登录注册框,固定DIV,底层阴影
<!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=gb2312" /> <title>JS当前页面登录注册框,固定DIV,底层阴影 - 计划 - 博客园</title> <!-- 一个按钮 点击之后 显示一个div div要水平 垂直居中 当我浏览器高度 宽度变化的时候 div依然水平 垂直居中 点击遮罩层,浮动层隐藏 知识点: .如何用css控制div水平垂直居中 .如何用js取得浏览器高度宽度 .如何控制resize事件--> <style type="text/css"> .hidden{ display:none} /*评论浮动层*/ #smallLay{width:498px; height:100px;padding:4px 10px 10px;background-color:#FFFFFF;border:1px solid #05549d;color:#333333;line-height:24px;text-align:left;-webkit-box-shadow:5px 2px 6px #000;-moz-box-shadow:3px 3px 6px #555;} </style> </head> <script type="text/javascript"> //判断浏览器ie6创建的div的样式和非ie6创建的div的样式 //创建div function showid(idname) { var isIE = (document.all) ? true : false; var isIE6 = isIE && ([/MSIE (\d)\.0/i.exec(navigator.userAgent)][0][1] == 6); var newbox = document.getElementById(idname); newbox.style.zIndex = "9999"; newbox.style.display = "block" newbox.style.position = !isIE6 ? "fixed" : "absolute"; newbox.style.top = newbox.style.left = "50%"; newbox.style.marginTop = -newbox.offsetHeight / 2 + "px"; newbox.style.marginLeft = -newbox.offsetWidth / 2 + "px"; var jihualayer = document.createElement("div"); jihualayer.id = "jihualayer"; jihualayer.style.width = jihualayer.style.height = "100%"; jihualayer.style.position = !isIE6 ? "fixed" : "absolute"; jihualayer.style.top = jihualayer.style.left = 0; jihualayer.style.backgroundColor = "#000"; jihualayer.style.zIndex = "9998"; jihualayer.style.opacity = "0.6"; document.body.appendChild(jihualayer); var sel = document.getElementsByTagName("select"); for (var i = 0; i < sel.length; i++) { sel[i].style.visibility = "hidden"; } function jihualayer_iestyle() { jihualayer.style.width = Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth) + "px"; jihualayer.style.height = Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight) + "px"; } function newbox_iestyle() { newbox.style.marginTop = document.documentElement.scrollTop - newbox.offsetHeight / 2 + "px"; newbox.style.marginLeft = document.documentElement.scrollLeft - newbox.offsetWidth / 2 + "px"; } if (isIE) { jihualayer.style.filter = "alpha(opacity=60)"; } if (isIE6) { jihualayer_iestyle() newbox_iestyle(); window.attachEvent("onscroll", function () { newbox_iestyle(); }) window.attachEvent("onresize", jihualayer_iestyle) } jihualayer.onclick = function () { newbox.style.display = "none"; jihualayer.style.display = "none"; for (var i = 0; i < sel.length; i++) { sel[i].style.visibility = "visible"; } } } </script> <body> <div style="width:200px; height:100px;"></div> <input name="" type="button" id="showbtn" value="点击显示" onclick="showid('smallLay')" /> <!--收藏浮层开始--> <div id="smallLay" style="display:none" > 这<a href="http://keleyi.com" style="text-decoration:none; color:Gray;">是</a>悬浮层 </div> <!--收藏浮层结束--> <div id="a" style="height:1000px;">这<a href="http://keleyi.com" style="text-decoration:none; color:Black;">是</a>普通层 <a href="http://keleyi.com/a/bjac/fybj7dyi.htm" target="_blank">原文</a></div> </body> </html>
17. 获取页面选中文本(支持IE、Firefox、Chrome、Safari、Opera) http://keleyi.com/a/bjac/e9n33nsb.htm
function getSelectionText() { if (window.getSelection) { //如果是Firefox、Chrome、Safari、Opera return window.getSelection().toString(); } else if (document.selection && document.selection.createRange) { //如果是IE return copytext_keleyi_com = document.selection.createRange().text; } return ''; }
18. 彩图变灰
<!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> <title>js使彩图变灰--柯乐义</title> <script src="http://keleyi.com/keleyi/phtml/image/3/grayscale.js" type="text/javascript"></script> </head> <body> js使彩图变灰,支持IE和Opera,不支持Chrome,<a href="http://keleyi.com/a/bjac/n2lodhc5.htm">原文</a><br /> <img src="http://keleyi.com/keleyi/phtml/image/3/mm1.jpg" alt="美女" /> <img src="http://keleyi.com/keleyi/phtml/image/3/mm1.jpg" alt="美女" id="gray" /> <br /> <img src="http://keleyi.com/keleyi/phtml/image/img/bmw_m3_gt.jpg" alt="美女与赛车" /><br /> <img src="http://keleyi.com/keleyi/phtml/image/img/bmw_m3_gt.jpg" alt="美女与赛车" id="car" /> <script type="text/javascript"> grayscale(document.getElementById("gray")); grayscale(document.getElementById("car")); </script> </body> </html>
19. 图片延迟加载
使用方法: 1.导入JS插件 <script src="http://keleyi.com/keleyi/pmedia/jquery-1.9.1.min.js" type="text/javascript"></script> <script src="http://keleyi.com/keleyi/phtml/image/jquery.lazyload.js" type="text/javascript"></script> 2.在你的页面中加入如下的javascript: $("img").lazyload(); 这将会使所有的图片都延迟加载。 当然插件还有几个配置项可供设置。 1.改变threshold $(“img”).lazyload({ threshold : 200 }); 把阀值设置成200 意思就是当图片没有看到之前先load 200像素。 2.当然了你也可以通过设置占位符图片和自定事件来触发加载图片事件 复制代码 代码如下: $("img").lazyload({ placeholder : "img/grey.gif", event : "click" }); 3.可以通过定义effect 参数来定义一些图片显示效果 复制代码 代码如下: $("img").lazyload({ placeholder : "img/grey.gif", effect : "fadeIn" }); LazyLoad(延迟加载)技术不仅仅用在对网页中图片的延迟加载,对数据同样可以,Google Reader和Bing图片搜索就把 LazyLoad技术运用的淋漓尽致; 缺陷: 1.与Ajax技术的冲突; 2.图片的延迟加载,遇到高度特别高的图片,会出现停止加载的问题; 3.写代码不规范的同学要注意了,不管由于什么原因,如果您的页面中,img标签的height属性未定义,那么我建议您最好不要使用ImageLazyLoad <!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" /> <title>图片延迟加载-柯乐义</title> <script type="text/javascript" src="http://keleyi.com/keleyi/pmedia/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="http://keleyi.com/keleyi/phtml/image/jquery.lazyload.js"></script> </head> <body> jquery实现图片延迟加载效果 <a href="http://keleyi.com/a/bjac/et551617.htm" target="_blank">原文</a><br /> <img src="http://keleyi.com/keleyi/phtml/image/img/grey.gif" data-original="http://keleyi.com/keleyi/phtml/image/img/bmw_m1_hood.jpg" width="765" height="574" alt="BMW M1 Hood keleyi.com" /><br /> <img src="http://keleyi.com/keleyi/phtml/image/img/grey.gif" data-original="http://keleyi.com/keleyi/phtml/image/img/bmw_m1_side.jpg" width="765" height="574" alt="BMW M1 Side keleyi.com" /><br /> <img src="http://keleyi.com/keleyi/phtml/image/img/grey.gif" data-original="http://keleyi.com/keleyi/phtml/image/img/viper_1.jpg" width="765" height="574" alt="Viper 1 keleyi.com" /> <img src="http://keleyi.com/keleyi/phtml/image/img/grey.gif" data-original="http://keleyi.com/keleyi/phtml/image/img/viper_corner.jpg" width="765" height="574" alt="Viper Corner keleyi.com" /><br /> <img src="http://keleyi.com/keleyi/phtml/image/img/grey.gif" data-original="http://keleyi.com/keleyi/phtml/image/img/bmw_m3_gt.jpg" width="765" height="574" alt="BMW M3 GT keleyi.com" /> <img src="http://keleyi.com/keleyi/phtml/image/img/grey.gif" data-original="http://keleyi.com/keleyi/phtml/image/img/corvette_pitstop.jpg" width="765" height="574" alt="Corvette Pitstop keleyi.com" /> <script type="text/javascript" charset="utf-8"> $(function () { $("img").lazyload({ effect: "fadeIn" }); }); </script> </body> </html>
20. jquery使用ColorBox弹出图片组浏览层
<!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> <title>使用ColorBox弹出图片组浏览层</title> <link rel="stylesheet" href="http://keleyi.com/keleyi/phtml/colorbox/colorbox.css" /> <script type="text/javascript" src="http://keleyi.com/keleyi/pmedia/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="http://keleyi.com/keleyi/phtml/colorbox/jquery.colorbox-min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".keleyi_com").colorbox({ rel: 'group1', transition: "none", innerWidth: '700px' }); }); </script> </head> <body> <div style="width:400px;margin-left:auto;margin-right:auto;"> 请点击下面链接,即可在弹出层显示图片组。 <p><a class="keleyi_com" href="http://keleyi.com/keleyi/phtml/picnext/images/k02.jpg" title="菊花">图片一</a></p> <p><a class="keleyi_com" href="http://keleyi.com/keleyi/phtml/picnext/images/k03.jpg" title="开心">图片二</a></p> <p><a class="keleyi_com" href="http://keleyi.com/keleyi/phtml/picnext/images/k05.jpg" title="宋慧乔">图片三</a></p> <p><a class="keleyi_com" href="http://keleyi.com/keleyi/phtml/picqiehuan/p3.jpg" title="梦想">图片四</a></p> </div></body> </html>
21. HTML5和jQuery实现彩图变灰与还原
<script type="text/javascript"> // $(".item img").css({"display":"none"); // On window load. This waits until images have loaded which is essential $(window).load(function () { // Fade in images so there isn't a color "pop" document load and then on window load $(".item img").animate({ opacity: 1 }, 500); // clone image $('.item img').each(function () { var el = $(this); el.css({ "position": "absolute" }).wrap("<div class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale').css({ "position": "absolute", "z-index": "998", "opacity": "0" }).insertBefore(el).queue(function () { var el = $(this); el.parent().css({ "width": this.width, "height": this.height }); el.dequeue(); }); this.src = grayscale(this.src); }); // Fade image $('.item img').mouseover(function () { $(this).parent().find('img:first').stop().animate({ opacity: 1 }, 1000); }) $('.img_grayscale').mouseout(function () { $(this).stop().animate({ opacity: 0 }, 1000); }); }); // Grayscale w canvas method function grayscale(src) { var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var imgObj = new Image(); imgObj.src = src; canvas.width = imgObj.width; canvas.height = imgObj.height; ctx.drawImage(imgObj, 0, 0); var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height); for (var y = 0; y < imgPixels.height; y++) { for (var x = 0; x < imgPixels.width; x++) { var i = (y * 4) * imgPixels.width + x * 4; var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3; imgPixels.data[i] = avg; imgPixels.data[i + 1] = avg; imgPixels.data[i + 2] = avg; } } ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height); return canvas.toDataURL(); } </script>