美文网首页web前端开发
原生JS实现可横向拖拽div方法

原生JS实现可横向拖拽div方法

作者: Eternal丶星空 | 来源:发表于2018-02-15 01:15 被阅读41次

    function dragDiv(doucument,className){
    var theobject = null; //声明,初始化一个操作对象

    function resizeObject() {
    this.el = null; //要操作的元素
    this.grabx = null; //一些常用值 元素相对于浏览器窗口的X轴位置
    this.graby = null; //元素相对于浏览器窗口的Y轴位置
    this.width = null; //元素offsetWidth宽度
    this.height = null; //元素offsetHeight高度
    }

    function doDown() {
    //判断元素是否满足条件,并且返回
    var el = getReal(event.srcElement, "className", class);

    //判断元素是否为空
    if (el == null) {
    theobject = null;
    return;
    }

    //构建一个被操作的元素对象
    theobject = new resizeObject();
    theobject.el = el;
    theobject.grabx = window.event.clientX;
    theobject.graby = window.event.clientY;
    theobject.width = el.offsetWidth;
    theobject.left = el.offsetLeft;

    window.event.returnValue = false;//取消事件处理程序中调用函数的默认操作
    window.event.cancelBubble = true;//取消冒泡
    }

    //把操作的元素置为空
    function doUp() {
    if (theobject != null) {
    theobject = null;
    }
    }

    //
    function doMove() {
    var el, xPos, str, xMin;
    xMin = 0; //最小移动宽度x

    //判断,且获取要操作的对象
    el = getReal(event.srcElement, "className", class);
    //判断上一步操作是否成功
    if (el.className == class说) {

    //设置cursor样式
    str = "pointer";
    el.style.cursor = str;
    }

    //开始拖拉的位置
    if(theobject != null) {
    theobject.el.style.width = Math.max(xMin, theobject.width + window.event.clientX - theobject.grabx) + "px";

    window.event.returnValue = false;//阻止事件默认
    window.event.cancelBubble = true;//阻止事件冒泡
    }
    }

    //判断当前的元素是否合格(不为空,不能为body)
    //判断当前元素的CSS类名是否为指定类名
    function getReal(el, type, value) {
    temp = el;
    while ((temp != null) && (temp.tagName != "BODY")) {
    if (eval("temp." + type) == value) {
    el = temp;
    return el;
    }
    temp = temp.parentElement;
    }
    return el;
    }

    document.onmousedown = doDown;
    document.onmouseup = doUp;
    document.onmousemove = doMove;
    }

    相关文章

      网友评论

        本文标题:原生JS实现可横向拖拽div方法

        本文链接:https://www.haomeiwen.com/subject/yggugxtx.html