js常用事件整理—兼容所有浏览器

1.鼠标滚动事件。

说明:返回值 大于0向上滚动,小于0向下滚动。

兼容型:所有浏览器。

代码:

/*********************** 
* 函数:鼠标滚动方向
* 参数:event
* 返回:滚轮方向[向上(大于0)、向下(小于0)]
************************
*/
var scrollFunc = function(e) {
var direct = 0;
e = e || window.event;
if (e.wheelDelta) {//IE/Opera/Chrome
direct = e.wheelDelta;
} else if (e.detail) {//Firefox
direct = e.detail;
}
// 返回值
alert(direct);
}
/*注册事件*/
if (document.addEventListener) {
document.addEventListener('DOMMouseScroll', scrollFunc, false);
}
//W3C
document.onmousewheel = scrollFunc; //IE/Opera/Chrome


2.获取滚动条高度。

兼容性:所有浏览器。

代码:

// 滚动条的高度
function getScrollTop() {
var scrollTop = 0;
if (document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop;
}
else if (document.body) {
scrollTop = document.body.scrollTop;
}
return scrollTop;
}


3.去掉所有html文本标记的js


function delHtmlTag(str)
{
return str.replace(/<[^>]+>/g,"");//去掉所有的html标记
}

4.字节长度查询

// 返回字节长度byte
function GetBytes(obj) {
    var byteLegth = 0;
    if (null != obj) {
        for (var i = 0; i < obj.length; i++) {
            if (obj.charCodeAt(i) >= 0 && obj.charCodeAt(i) <= 255) {
                byteLegth++;
            }
            else {
                byteLegth = byteLegth + 2;
            }
        }
    }
    return byteLegth;
}

5.字节长度截取

// 字符截取
function titleSetLeg(obj) {
    var tit = jQuery(obj).val();
    var leg = 26;   // 截取长度
    if (GetBytes(tit) > leg) {
        // 字符截取操作
        for (var i = 0; i < leg; i++) {
            if (!(tit.charCodeAt(i) >= 0 && tit.charCodeAt(i) <= 255)) {
                // 汉字
                leg--;
            }
        }
        jQuery(obj).val(tit.substring(0, leg));
    }
}
关注下面二维码,订阅更多精彩内容。
微信打赏
关注公众号(加好友):

原文地址:https://www.cnblogs.com/vipstone/p/2248561.html