前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >js实用方法记录-指不定哪天就会用到的js方法

js实用方法记录-指不定哪天就会用到的js方法

作者头像
易墨
发布2018-09-14 15:44:33
1.2K0
发布2018-09-14 15:44:33
举报

js实用方法记录-指不定哪天就会用到的js方法

常用或者不常用都有

判断是否在微信浏览器中

测试代码:isWeiXin()==false

代码语言:javascript
复制
/**
 * 是否在微信中
 */
function isWeixin() {

  return (
    navigator.userAgent
      .toLowerCase()
      .indexOf('micromessenger') > -1
  )
}

全角转半角

测试代码:wholetoHalf('hello'')=='hello'

代码语言:javascript
复制
/**
 * 转换全角字符串
 * @param {string} txt 含全角字符串
 */
function wholetoHalf(txt){
    if (!txt) {
        return txt;
    }
    var tmp = "";
    for (var i = 0; i < txt.length; i++) {
        if (txt.charCodeAt(i) > 65280 && txt.charCodeAt(i) < 65375) {
            tmp += String.fromCharCode(txt.charCodeAt(i) - 65248);
        }
        else if (txt.charCodeAt(i) == 12288) {
            tmp += String.fromCharCode(32);
        }
        else {
            tmp += String.fromCharCode(txt.charCodeAt(i));
        }
    }
    return tmp;
}

生成Guid

代码语言:javascript
复制
/**
 * 生成Guid
 */
function genGuid() {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return (S4() + S4() + "-" + S4() + "-4" + S4().substr(0, 3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();
}

获取滚动条距顶部距离

代码语言:javascript
复制
/**
 * 获取滚动条距顶部距离
 */
function getScrollTop() {
    var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
    if (document.body) {
        bodyScrollTop = document.body.scrollTop;
    }
    if (document.documentElement) {
        documentScrollTop = document.documentElement.scrollTop;
    }
    scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
    return scrollTop;
}

获取滚动条高度

代码语言:javascript
复制
/**
 * 获取滚动条高度 默认
 */
function getScrollHeight() {
    var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
    if (document.body) {
        bodyScrollHeight = document.body.scrollHeight;
    }
    if (document.documentElement) {
        documentScrollHeight = document.documentElement.scrollHeight;
    }
    scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
    return scrollHeight;
}

通过判断滚动条位置操作元素

代码语言:javascript
复制
if(getScrollHeight() > document.documentElement.clientHeight 
    && getScrollTop()>getScrollHeight()/4){//有滚动条且滚动条距离顶部在四分之外
    //显示回到顶部浮层什么的~~
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-05-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • js实用方法记录-指不定哪天就会用到的js方法
    • 判断是否在微信浏览器中
      • 全角转半角
        • 生成Guid
          • 获取滚动条距顶部距离
            • 获取滚动条高度
              • 通过判断滚动条位置操作元素
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档