• JS ul li 任意拖动位置


    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    </head>
    <body>
    <style>

    ul {
    list-style: none;
    margin: 200px;
    font-size: 0;
    }
    .ele {
    font-size: 16px;
    100px;
    height: 40px;
    border: 1px solid #999;
    background: #EA6E59;
    margin: 2px 0;
    border-radius: 10px;
    padding-left: 10px;
    color: white;
    cursor: move;
    }
    </style>
    <form id="form1" runat="server">
    <div>
    <ul id="container">
    <li class="ele" draggable="true">1</li>
    <li class="ele" draggable="true">2</li>
    <li class="ele" draggable="true">3</li>
    <li class="ele" draggable="true">4</li>
    <li class="ele" draggable="true">5</li>
    <li class="ele" draggable="true">6</li>
    <li class="ele" draggable="true">7</li>
    <li class="ele" draggable="true">8</li>
    </ul>
    </div>
    </form>
    </body>
    </html>
    <script>

    var node = document.querySelector("#container");
    var draging = null;
    //使用事件委托,将li的事件委托给ul
    node.ondragstart = function (event) {
    //firefox设置了setData后元素才能拖动!!!!
    event.dataTransfer.setData("te", event.target.innerText); //不能使用text,firefox会打开新tab
    draging = event.target;
    }
    node.ondragover = function (event) {
    event.preventDefault();
    var target = event.target;
    //因为dragover会发生在ul上,所以要判断是不是li
    if (target.nodeName === "LI" && target !== draging) {
    //_index是实现的获取index
    if (_index(draging) < _index(target)) {
    target.parentNode.insertBefore(draging, target.nextSibling);
    } else {
    target.parentNode.insertBefore(draging, target);
    }
    }
    }

    function _index(el) {
    var index = 0;
    if (!el || !el.parentNode) {
    return -1;
    }
    while (el && (el = el.previousElementSibling)) {
    index++;
    }
    return index;
    }
    </script>

  • 相关阅读:
    Spring(二) Spring装配Bean的几种方式
    Spring(一) Spring配置文件中classpath和classpath*的区别
    学习响应式编程 Reactor (5)
    学习响应式编程 Reactor (4)
    学习响应式编程 Reactor (3)
    学习响应式编程 Reactor (2)
    学习响应式编程 Reactor (1)
    学习Java 8 Stream Api (5)
    学习Java 8 Stream Api (4)
    Spring WebFlux 学习笔记
  • 原文地址:https://www.cnblogs.com/zhusk/p/11542450.html
Copyright © 2020-2023  润新知