JS Code block 代码块–dom

星期二, 2023-04-18 | Author: Lee | computer, 前端 | 1,050 views

dom
获取一级子节点
获取兄弟节点
获取元素相对于视口的位置信息
判定节点里是否有class
添加class
删除class
替换class
dom对象转换成字符串
给页面添加js和css
禁用浏览器的默认行为
获取当前元素,或窗口的滚动位置
判断一个对象是否为Dom对象
获取HTML里的文字内容
字符串的转义
字符串的反转义
将文本插入到文本区域的光标位置
浏览器全屏
退出全屏
是否是Element

/**
 * 获取一级子节点
 * @param obj 父节点
 * @return {Array}
 */
getChildren (obj) {
    let objChild = [] ;
    let objs = obj.getElementsByTagName('*');
    for (let i = 0, j = objs.length; i < j; ++i) {
        if (objs[i].nodeType !== 1) { alert(objs[i].nodeType)
            continue
        }
        let temp = objs[i].parentNode;
        if (temp.nodeType == 1) {
            if (temp == obj) {
                objChild[objChild.length] = objs[i]
            }
        } else if (temp.parentNode == obj) {
            objChild[objChild.length] = objs[i]
        }
    }
    return objChild
}
 
/**
 * 获取兄弟节点
 */
function siblings (element) {
    let chid = element.parentNode.children, eleMatch = [];
    for(let i = 0, len = chid.length; i < len; i ++){
        if(chid[i] != element){
            eleMatch.push(chid[i]);
        }
    }
    return eleMatch;
}
 
/**
 * 获取元素相对于视口的位置信息
 *
 * @param {Element} ele
 */
const getOffsetRect = (ele) => {
    const box = ele.getBoundingClientRect();
    const body = document.body;
    const docElem = document.documentElement;
    // 获取页面的scrollTop,scrollLeft(兼容性写法)
    const scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
    const scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
    const clientTop = docElem.clientTop || body.clientTop;
    const clientLeft = docElem.clientLeft || body.clientLeft;
    const top = box.top + scrollTop - clientTop;
    const left = box.left + scrollLeft - clientLeft;
    return {
        // Math.round 兼容火狐浏览器bug
        top: Math.round(top),
        left: Math.round(left)
    };
};
 
/**
* 判定节点里是否有class
* @param elements dom节点
* @param cName class名
* @return {boolean}
*/
function hasClass (element, cName) {
  return !!element.className.match(new RegExp('(\\s|^)' + cName + '(\\s|$)'))
}
 
/**
* 添加class
* @param elements
* @param cName
*/
function addClass (element, cName) {
  if (!hasClass(element, cName)) {
    element.className += ' ' + cName
  }
}
 
/**
* 删除class
* @param elements
* @param cName
*/
function removeClass (element, cName) {
  if (hasClass(element, cName)) {
    element.className = element.className.replace(new RegExp('(\\s|^)' + cName + '(\\s|$)'), ' ')
  }
}
 
/**
 * 替换class
 * */
function replaceClass (element, newName, oldName) {
    removeClass(element, oldName);
    addClass(element, newName);
}
 
/**
 * 将dom对象转换成字符串
 * @param node
 * @returns {string}
 */
function nodeToString ( node ) {
    let tmpNode = document.createElement( 'div');
    //appendChild()  参数Node对象   返回Node对象  Element方法
    //cloneNode()  参数布尔类型  返回Node对象   Element方法
    tmpNode.appendChild( node.cloneNode( true ) );
    let str = tmpNode.innerHTML;
    tmpNode = node = null; // prevent memory leaks in IE
    return str;
}
 
/**
 * 给页面添加js和css
 * @type {Array}
 */
let loadedPaths = [];
 
function delayLoadJSAndCSS(path, type, title, preFn) {
 
    if(loadedPaths.includes(path)) {
        return Promise.resolve();
    } else {
        return new Promise(function (resolve) {
            let s = null;
            let js = null;
            let less = null;
            let i = 0;
            if (!type) {
                type = path.substr(path.lastIndexOf('.') + 1);
            }
            if (type === 'js') {
                let ss = document.getElementsByTagName('script');
                for (i = 0; i < ss.length; i++) {
                    if (ss[i].src && ss[i].src.indexOf(path) != -1 || ss[i].title == title) {
                        js = ss[i];
                        resolve(ss[i]);
                    }
                }
                if (!js) {
                    s = document.createElement('script');
                    s.type = 'text/javascript';
                    s.src = path;
 
                    if (preFn) {
                        preFn(s);
                    }
 
                    if (title) {
                        s.title = title;
                    }
                    loadedPaths.push(path);
                }
            } else if (type === 'css') {
                let ls = document.getElementsByTagName('link');
                for (i = 0; i < ls.length; i++) {
                    if (ls[i].href && ls[i].href.indexOf(path) != -1 || ls[i].title == title) {
                        less = ls[i];
                        resolve(ls[i]);
                    }
                }
                if (!less) {
                    s = document.createElement('link');
                    s.rel = 'stylesheet';
                    s.type = 'text/css';
                    s.href = path;
                    if (title) {
                        s.title = title;
                    }
                    s.disabled = false;
                    loadedPaths.push(path);
                }
            } else {
                resolve(false);
            }
 
            if (s) {
                let head = document.getElementsByTagName('head')[0];
                head.appendChild(s);
                s.onload = function () {
                    resolve(s);
                };
            }
        });
    }
}
 
/**
* 禁用浏览器的默认行为
*/
function disableScreenElasticity() {
    // ios
    // 禁用不需要的浏览器默认行为
    let $win = $(window);
    // 禁止ios的浏览器容器弹性
    $win
        .on('scroll.elasticity', function (e) {
            e.preventDefault();
        })
        .on('touchmove.elasticity', function (e) {
            e.preventDefault();
        });
 
    // 禁止拖动图片
    $win.delegate('img', 'mousemove', function (e) {
        e.preventDefault();
    });
}
 
/**
 * 获取当前元素,或窗口的滚动位置
 * @param el
 * @return {{x: number, y: number}}
 */
function getScrollPosition(el = window) {
    return {
        x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
        y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop
    }
}
 
/**
 * 判断一个对象是否为Dom对象
 * @param   {Object}   obj
 * @return  {Boolean}
 */
function isDom (obj) {
    return obj && obj.nodeType === 1 && typeof(obj.nodeName) == 'string'
}
 
/**
 * 获取HTML里的文字内容
 * @param {string} str html字符串
 * @return {string} 处理后的文字
 * @example
 * getDecodeHTMLText('<li>111<span>222</span></li>')
 */
function getDecodeHTMLText(str){
    const element = document.createElement('div');
    if (str && typeof str === 'string') {
        // strip script/html tags
        str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
        str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
        element.innerHTML = str;
        str = element.textContent;
        element.textContent = '';
    }
    return str;
}
 
/**
 * 字符串的转义,将`&`, `<`, `>`, `"`, `'`分别转义为`&amp;`, `&lt;`,  `&gt;`, `&quot;`, `&#x27;`
 * @param {string} text处理前字符串
 * @return {string} 处理后的字符串
 * @runkit true
 * @example
 * getEscapeText('<hello>')
 * // '&lt;hello&gt;'
 */
function getEscapeText(text) {
    const _escape = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#x27;'
    }
    const escapeExpr = /(&|<|>|"|')/g
    return ('' + text).replace(escapeExpr, function (match) {
        return _escape[match]
    });
}
 
/**
 * 字符串的反转义,将`&amp;`, `&lt;`,  `&gt;`, `&quot;`, `&#x27;`替换为转义前的符号
 * @param {string} text 处理前字符串
 * @return {string} 处理后的字符串
 * @runkit true
 * @example
 * getUnescapeText('&lt;hello&gt;')
 * // '<hello>'
 */
function getUnescapeText(text) {
    const _unescape = {
        '&amp;': '&',
        '&lt;': '<',
        '&gt;': '>',
        '&quot;': '"',
        '&#x27;': "'"
    }
    const unescapeExpr = /(&amp;|&lt;|&gt;|&quot;|&#x27;)/g;
    return ('' + text).replace(unescapeExpr, function (match) {
        return _unescape[match];
    });
}
 
/**
 * 将文本插入到文本区域的光标位置
 * _应用场景:_如在评论框里,在光标位置里插入emoji等
 * @param {object} dom对象
 * @param {string} str
 * @example
 * <textarea name="textarea" rows="10" cols="50">你好世界~</textarea>
 * const editText = document.querySelector('#editText');
 * insertText(editText, 'hello world');
 * // =>
 */
function insertAtCaret(dom, str = '') {
  if (document.selection) { // IE
    let sel = document.selection.createRange();
    sel.text = str;
  } else if (typeof dom.selectionStart === 'number' && typeof dom.selectionEnd === 'number') {
    let startPos = dom.selectionStart;
    let endPos = dom.selectionEnd;
    let cursorPos = startPos;
    let tmpStr = dom.value;
 
    dom.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);
    cursorPos += str.length;
    dom.selectionStart = dom.selectionEnd = cursorPos;
  } else {
    dom.value += str;
  }
}
    /**
     * 全屏
    */
    let toFullScreen = () => {
        let el = document.documentElement;
        let rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen;
 
        //typeof rfs != "undefined" && rfs
        if (rfs) {
            rfs.call(el);
        } else if (typeof window.ActiveXObject !== "undefined") {
            //for IE,这里其实就是模拟了按下键盘的F11,使浏览器全屏
            let wscript = new ActiveXObject("WScript.Shell");
            if (wscript != null) {
                wscript.SendKeys("{F11}");
            }
        } else {
            alert("浏览器不支持全屏");
        }
    }
 
    /**
     * 退出全屏
    */
    let exitFullscreen = function () {
        let el = parent.document;
        let cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen;
 
        //typeof cfs != "undefined" && cfs
        if (cfs) {
            cfs.call(el);
        } else if (typeof window.ActiveXObject !== "undefined") {
            //for IE,这里和fullScreen相同,模拟按下F11键退出全屏
            let wscript = new ActiveXObject("WScript.Shell");
            if (wscript != null) {
                wscript.SendKeys("{F11}");
            }
        } else {
            alert("切换失败,可尝试Esc退出")
        }
    }
/**
* 是否是Element
* @param el
* @return {*|boolean}
*/
function isElement(el) {
   return el && el.nodeType === Node.ELEMENT_NODE     
}

Tags:

文章作者: Lee

本文地址: https://www.pomelolee.com/2391.html

除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址

No comments yet.

Leave a comment

Search

文章分类

Links

Meta