$(document).ready(function(){// 这条命令会使得html页面全部加载完毕才会执行内容 原生js代替: window.onload = function(){}var index =0// 切换图片的函数varswiper=function(){$('img').eq(index).css({'opacity':'1'})// display也可.siblings().css({'opacity':'0'})}$('a').mouseenter(function(){// console.log($('a').length);// console.log($(this).index()); // 从0开始
index =$(this).index()// $(this).index() 确定鼠标进入的是第几个图片swiper()})// 实现向左向右键控制图片的改变$(document).keydown(function(e){// console.log(e); // 打印向右键键值39;向左键键值37if(e.keyCode ==37){// if(index==0) {// index = $('a').length - 1// } else {// index --// }// 精简写法:三目
index = index >0?-- index :$('a').length-1}elseif(e.keyCode ==39){// if(index == $('a').length-1){// index = 0// } else {// index ++// }// 精简写法:三目
index = index <$('a').length-1?++ index :0}else{returnfalse}swiper()});})// 写法二// 绑定事件写法$('a').add(document).on({// 此处只写$(document)时,进入事件不能精准到a标签,且document是一个整体的集合,不要随便加
mouseenter:function(e){
e.stopPropagation();
index =$(this).index()
swiper
},
keydown:function(e){if(e.keyCode ==37){
index = index >0?-- index :$('a').length-1}elseif(e.keyCode ==39){
index = index <$('a').length-1?++ index :0}else{returnfalse// 这个false会阻止除了左右键其他键的作用,改为true也可}swiper()}})// 动画样式编辑varswiper=function(){$('img').eq(index).stop()// 加上stop来停止上一个动画.animate({'opacity':'1'},1000)// 用animation时,display不可以,需要的是有具体值的属性.siblings().stop().animate({'opacity':'0'},1000)}