欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaScript实现新闻列表上下移动效果

程序员文章站 2022-07-14 16:46:04
...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript实现新闻列表上下移动效果</title>
<style>
* {margin:0; padding:0; list-style:none;}
#ul1 {width:600px; margin:10px auto;}
#ul1 li {border:1px solid #CCC; padding:4px;}
#ul1 span {width:500px; display:inline-block;}
</style>
</head>
<body>
<ul id="ul1">
    <li>
        <span>newlist111111</span>
        <a href="javascript:;" class="prev">上移</a>
        <a href="javascript:;" class="next">下移</a>
    </li>
    <li>
        <span>newlist111111</span>
        <a href="javascript:;" class="prev">上移</a>
        <a href="javascript:;" class="next">下移</a>
    </li>
    <li>
        <span>newlist111111</span>
        <a href="javascript:;" class="prev">上移</a>
        <a href="javascript:;" class="next">下移</a>
    </li>
    <li>
        <span>newlist111111</span>
        <a href="javascript:;" class="prev">上移</a>
        <a href="javascript:;" class="next">下移</a>
    </li>
</ul>


<script>
    window.onload = function(){
        var oUl = document.getElementById('ul1');
        var aBtn = oUl.getElementsByTagName('a');
        for(var i = 0;i<aBtn.length;i++){
            if(i%2==0){
                aBtn[i].onclick = function(){
                var obj = this.parentNode;
                if(obj == oUl.children[0]){
                    alert('已经到顶了');
                    return;
                }
                var oPrev = obj.previousElementSibling||obj.previousSibling;
                oUl.insertBefore(obj,oPrev);
            };
            }else{
                aBtn[i].onclick = function(){
                    var obj = this.parentNode;
                    if(obj == oUl.children[oUl.children.length-1]){
                        alert('已经到底了');
                        return;
                    }
                    var oNext = obj.nextElementSibling||obj.nextSibling;
                    var oNext2 = oNext.nextElementSibling||oNext.nextSibling;
                    oUl.insertBefore(obj,oNext2);   
                };
            }
        }
    };
</script>
</body>
</html>