broswer.js 2.93 KB
/**
 * 浏览器相关功能扩展
 * @author: liqi <qi.li@yoho.cn>
 * @date: 2016/11/26
 */

var $ = require('yoho-jquery');

var state;
var isHidden;
var changeEvent;

/**
 * 获取光标位置
 */
function _getCursorPosition() {
    var sel,
        pos = 0,
        selLength,
        el = $(this).get(0);

    if ('selectionStart' in el) {
        pos = el.selectionStart;
    } else if ('selection' in document) {
        sel = document.selection.createRange();
        selLength = document.selection.createRange().text.length;

        el.focus();
        sel.moveStart('character', -el.value.length);
        pos = sel.text.length - selLength;
    }
    return pos;
}

/**
 * 判断当前tab页是否可见
 */
function tabIsHidden() {
    if (typeof document.hidden !== 'undefined') {
        changeEvent = 'visibilitychange';
        state = 'visibilityState';
    } else if (typeof document.mozHidden !== 'undefined') {
        changeEvent = 'mozvisibilitychange';
        state = 'mozVisibilityState';
    } else if (typeof document.msHidden !== 'undefined') {
        changeEvent = 'msvisibilitychange';
        state = 'msVisibilityState';
    } else if (typeof document.webkitHidden !== 'undefined') {
        changeEvent = 'webkitvisibilitychange';
        state = 'webkitVisibilityState';
    }
    return document[state] === 'hidden';
}

/**
 * 判断当前tab页可见
 * @param callback 可见回调
 */
function tabVisible(callback) {
    isHidden = tabIsHidden();
    document.addEventListener(changeEvent, function() {
        if (!isHidden) {
            if (callback) {
                return callback();
            }
        }
    }, false);
}

/**
 * 设置光标位置
 * @param el 元素
 * @param pos 位置
 */
function setCursor(el, pos) {
    var range;

    if (el.setSelectionRange) {
        // chrome and firefox support
        el.setSelectionRange(pos, pos);
        el.focus();
    } else if (el.createTextRange) {
        // IE support
        range = el.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}

/**
 * 回车发送
 * 回车 & CTRL 换行
 * @param e 事件
 * @param fn 回车事件
 */
function ctrlEnter(e, send) {
    var code = e.keyCode,
        tag = $(e.target),
        val = tag.val(),
        pos = tag.getCursorPosition(),
        start = val.substring(0, pos),
        end = val.substring(pos),
        newVal = [start, '\n', end].join(''),
        ctrlLike = e.ctrlKey || e.metaKey;

    if (code !== 13) {
        return;
    }

    if (!ctrlLike) {
        e.preventDefault();
        send(e);
    } else {
        tag.val(newVal);
        setCursor(tag[0], pos + 1);
    }
}

// 获取光标位置
// jquery.fn.extend
$.fn.extend({
    getCursorPosition: _getCursorPosition
});

module.exports = {
    ctrlEnter: ctrlEnter,
    setCursor: setCursor,
    tabVisible: tabVisible,
    tabIsHidden: tabIsHidden
};