2 qq 31788907 qq_31788907 于 2016.04.21 11:11 提问

Jquery语句换成JS写这段

图片说明求大神帮忙 第二句是别人打给我参考的

2个回答

perhapschen
perhapschen   2016.04.21 22:08
已采纳

看下代码,真挺麻烦

 <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
li {float:left; height:50px; width:50px; background:#ccc; list-style:none; margin-left:5px;}
li.curr {background:red;}
</style>
<script type='text/javascript'>
function hasClass(obj, sCls){   
    return obj.className.match(new RegExp("\\b"+sCls+"\\b", "i"));      
}
function addClass(obj, sCls){   
    var blank=(obj.className!="")?" ":"";
    if(!hasClass(obj, sCls))obj.className+=blank+sCls;  
}

function removeClass(obj, sCls){    
    var re=new RegExp("(\\s|^)"+sCls+"(\\s|$)", "i");
    if(hasClass(obj, sCls))obj.className=obj.className.replace(re, ""); 
}
function prevAll(arr,sCls){
    var index=0;
    for(var i=0;i<arr.length;i++){
        if(hasClass(arr[i],sCls))index=i;
    }
    return index;
}
window.onload=function(){
    var aLi=document.getElementsByTagName('li'), index;

    var movePrev = function (){
        index=prevAll(aLi,'curr');
        if(index==0){//可循环移动
            removeClass(aLi[index],'curr');
            addClass(aLi[aLi.length-1],'curr');
            index = aLi.length-1;
            console.log(index);
        }else{
            removeClass(aLi[index],'curr');
            addClass(aLi[index-1],'curr');
            index--;
            console.log(index);
        }
    }       
    var moveNext = function (){
        index=prevAll(aLi,'curr');
        if(index==aLi.length-1){//可循环移动
            removeClass(aLi[aLi.length-1],'curr');
            addClass(aLi[0],'curr');
            index = 0;
        }else{
            removeClass(aLi[index],'curr');
            addClass(aLi[index+1],'curr');
            index++;
        }                           
    }
    document.onkeydown=function(e){
        var e = e || event,
        code = e.keyCode || e.which;
        code==38 && movePrev();
        code==40 && moveNext();             
    }

};
</script>
</head>
<body>
<ul>
    <li class='curr'></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>
</body>
</html>
perhapschen
perhapschen   2016.04.21 20:24

把JQ改写成JS那就麻烦多了,其实你现在的代码已经是JQ、JS混写了

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!