为什么第一个李元素不要向下移动?

时间:2016-08-11 22:31:39

标签: javascript jquery

这是我的代码:

<html>
    <head>
        <style>
            ul,li {
                position:relative;
            }
        </style>
    </head>
    <body>
        <ul>
            <li class="c1">This is 1</li>
             <li class="c2">This is 2</li>
             <li class="c3">This is 3</li>
        </ul>
        <br>
        <button>Move</button>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            $("button").on("click",function(){
                $c = $(".c2").clone(true);
                $c.attr({class:""});
                $c.insertAfter(".c2");
                var y = $(".c2").position();
                var x = ($(".c2").insertBefore(".c1")).position();
                $(".c2").hide();
                $c.css({position:"absolute"}).animate({"top":x.top,"left":x.left},{duration:1000});
            })
        </script>
    </body>
</html>

为什么<li class="c1">This is 1</li>不要向下移动?并与<li class="c2">This is 2</li>叠加?

1 个答案:

答案 0 :(得分:1)

您将第二个li元素定位为absolute,因此它与第一个元素重叠。

这是html的结果(点击按钮后):

&#13;
&#13;
ul,li {
  position:relative;
}
&#13;
<ul>
  <li class="c2" style="display: none;">This is 2</li>
  <li class="c1">This is 1</li>
  <li class="" style="position: absolute; top: 0px; left: 40px;">This is 2</li>
  <li class="c3">This is 3</li>
</ul>
&#13;
&#13;
&#13;

如果你想在这两个元素之间进行交换,你可以使用这个代码:

&#13;
&#13;
$("button").on("click",function(){
  c1pos = $(".c1").position();
  c2pos = $(".c2").position();
  
  $c1 = $(".c1").clone(true);
  $c1.attr({class:""});
  $c1.insertAfter(".c1");
    
  $c2 = $(".c2").clone(true);
  $c2.attr({class:""});
  $c2.insertAfter(".c2");
  
  $(".c1,.c2").css('visibility', 'hidden');
  
  $c1.css({position:"absolute", "top":c1pos.top,"left":c1pos.left},{duration:1000});
  $c2.css({position:"absolute", "top":c2pos.top,"left":c2pos.left},{duration:1000});
  
  $c1.css({position:"absolute"}).animate({"top":c2pos.top,"left":c2pos.left},{duration:1000});
  $c2.css({position:"absolute"}).animate({"top":c1pos.top,"left":c1pos.left},{duration:1000});
})
&#13;
ul,li {
  position:relative;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<ul>
  <li class="c1">This is 1</li>
  <li class="c2">This is 2</li>
  <li class="c3">This is 3</li>
</ul>

<button>Move</button>
&#13;
&#13;
&#13;