在学原生JS之前,一直用jQuery 写运动,各种方便,但是不知其所以然,今天得空看了一个javascript 视频教程(这里不说了,以防广告的嫌疑),只能用一个词语形容之后的感觉-------醍醐灌顶。
/* - obj 指的是DOM对象 - json 指的是 CSS样式 - 例 startMove(oDiv,{width:100,height:100},function(){}) */ function startMove(obj,json,fnEnd){ clearInterval(obj.timer); //先清除之前的定时器 obj.timer = setInterval(function(){ var bStop = true; // 假设所有的值都到了 for( var attr in json ){ //遍历json属性 var cur = (attr == 'opacity') ? Math.round(parseFloat(getStyle(obj,attr))*100) : parseInt(getStyle(obj,attr)); //对opacity 特殊处理 var speed = (json[attr] - cur)/6; speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); //speed 数字转化,防止不能到达目标的bug if( cur != json[attr]) bStop = false; //如果没有达到目标值,则bStop设为false; if(attr == 'opacity'){ obj.style.filter = 'alpha(opacity='+ (cur + speed) +')'; obj.style.opacity = (cur + speed)/100; }else{ obj.style[attr] = cur + speed + 'px'; } } if(bStop){ clearInterval(obj.timer); if(fnEnd) fnEnd(); //执行回调函数 } },30); } function getStyle(obj,name){ return obj.currentStyle ? obj.currentStyle[name] : window.getComputedStyle(obj,null)[name]; //浏览器兼容性处理,注意getComputedStyle为只读属性 } function getByClass(oParent,sClass){ var aEle = oParent.getElementsByTagName('*'); var aResult =[]; var re = new RegExp('\\b' + sClass + '\\b','i'); for(var i=0; i<aEle.length;i++ ){ if(re.test(aEle[i].className)) aResult.push(aEle[i]); } return aResult; }
此框架可以实现大部分的运动效果,下面是我写的仿百度首页幻灯片:
window.onload = function(){ var oSlide = document.getElementById('slide'); var asmallpicWrap = getByClass(oSlide,'smallpic')[0]; var asmallUl = asmallpicWrap.getElementsByTagName('ul')[0]; var abigpicWrap = getByClass(oSlide,'bigpic')[0]; var asmallpic = asmallpicWrap.getElementsByTagName('li'); var obigpic = abigpicWrap.getElementsByTagName('img'); var oprev = getByClass(oSlide,'prev')[0]; var onext = getByClass(oSlide,'next')[0]; var nowIndex = 2; var now = 0; //大图切换 for(var i=0; i<asmallpic.length;i++ ){ asmallpic[i].index = i; asmallpic[i].onclick = function(){ if(this.index == now) return ; now = this.index; tab(); } asmallpic[i].onmouseover = function(){ startMove(this,{'opacity':100}); } asmallpic[i].onmouseout = function(){ if(this.index!=now){ startMove(this,{'opacity':60}); } tab(); } } function tab(){ obigpic[now].style.zIndex = nowIndex++; for(var i=0; i<asmallpic.length;i++ ){ startMove(asmallpic[i],{'opacity':60}); } startMove(asmallpic[now],{'opacity':100}); if(now <= 3){ startMove(asmallUl,{'left':0}); }else if(now == asmallpic.length-1){ startMove(asmallUl,{'left':-(now-4)*asmallpic[0].offsetWidth}); }else{ startMove(asmallUl,{'left':-(now-3)*asmallpic[0].offsetWidth}); } } //下一个 oprev.onclick = function(){ now--; if(now == -1 ){ now = asmallpic.length-1 } tab(); } //上一个 onext.onclick = function(){ now++; if(now == asmallpic.length ){ now = 0 } tab(); } var timer = setInterval(onext.onclick,3000); oSlide.onmouseover = function(){ clearInterval(timer); } oSlide.onmouseout = function(){ timer = setInterval(onext.onclick,3000); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2025-01-05 17:51:55