JavaScript常用工具函数汇总(二)

2,670次阅读
没有评论

共计 5008 个字符,预计需要花费 13 分钟才能阅读完成。

21 格式化 CSS 样式代码

function formatCss(s) {
  // 格式化代码
  s = s.replace(/s*([{}:;,])s*/g, "$1");
  s = s.replace(/;s*;/g, ";"); // 清除连续分号
  s = s.replace(/,[s.#d]*{/g, "{");
  s = s.replace(/([^s]){([^s])/g, "$1 {nt$2");
  s = s.replace(/([^s])}([^n]*)/g, "$1n}n$2");
  s = s.replace(/([^s]);([^s}])/g, "$1;nt$2");
  return s;
}

22 获取 cookie 值

function getCookie(name) {var arr = document.cookie.match(new RegExp("(^|)" + name + "=([^;]*)(;|$)"));
  if (arr != null) return unescape(arr[2]);
  return null;
}

23 获得 URL 中 GET 参数值

// 用法:如果地址是 test.htm?t1=1&t2=2&t3=3, 那么能取得:GET["t1"], GET["t2"], GET["t3"]
function getGet() {querystr = window.location.href.split("?");
  if (querystr[1]) {GETs = querystr[1].split("&");
    GET = [];
    for (i = 0; i < GETs.length; i++) {tmp_arr = GETs.split("=");
      key = tmp_arr[0];
      GET[key] = tmp_arr[1];
    }
  }
  return querystr[1];
}

24 获取移动设备初始化大小

function getInitZoom() {if (!this._initZoom) {var screenWidth = Math.min(screen.height, screen.width);
    if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) {screenWidth = screenWidth / window.devicePixelRatio;}
    this._initZoom = screenWidth / document.body.offsetWidth;
  }
  return this._initZoom;
}

25 获取页面高度

function getPageHeight() {
  var g = document,
    a = g.body,
    f = g.documentElement,
    d = g.compatMode == "BackCompat" ? a : g.documentElement;
  return Math.max(f.scrollHeight, a.scrollHeight, d.clientHeight);
}

26 获取页面 scrollLeft

function getPageScrollLeft() {
  var a = document;
  return a.documentElement.scrollLeft || a.body.scrollLeft;
}

27 获取页面 scrollTop

function getPageScrollTop() {
  var a = document;
  return a.documentElement.scrollTop || a.body.scrollTop;
}

28 获取页面可视宽度

function getPageViewWidth() {
  var d = document,
    a = d.compatMode == "BackCompat" ? d.body : d.documentElement;
  return a.clientWidth;
}

29 获取页面可视高度

function getPageViewHeight() {
  var d = document,
    a = d.compatMode == "BackCompat" ? d.body : d.documentElement;
  return a.clientHeight;
}

30 获取页面宽度

function getPageWidth() {
  var g = document,
    a = g.body,
    f = g.documentElement,
    d = g.compatMode == "BackCompat" ? a : g.documentElement;
  return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth);
}

31 获取移动设备屏幕宽度

function getScreenWidth() {var smallerSide = Math.min(screen.width, screen.height);
  var fixViewPortsExperiment =
    rendererModel.runningExperiments.FixViewport ||
    rendererModel.runningExperiments.fixviewport;
  var fixViewPortsExperimentRunning =
    fixViewPortsExperiment && fixViewPortsExperiment.toLowerCase() === "new";
  if (fixViewPortsExperiment) {if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) {smallerSide = smallerSide / window.devicePixelRatio;}
  }
  return smallerSide;
}

32 获取移动设备最大化大小

function getZoom() {
  var screenWidth =
    Math.abs(window.orientation) === 90
      ? Math.max(screen.height, screen.width)
      : Math.min(screen.height, screen.width);
  if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) {screenWidth = screenWidth / window.devicePixelRatio;}
  var FixViewPortsExperiment =
    rendererModel.runningExperiments.FixViewport ||
    rendererModel.runningExperiments.fixviewport;
  var FixViewPortsExperimentRunning =
    FixViewPortsExperiment &&
    (FixViewPortsExperiment === "New" || FixViewPortsExperiment === "new");
  if (FixViewPortsExperimentRunning) {return screenWidth / window.innerWidth;} else {return screenWidth / document.body.offsetWidth;}
}

33 获取网页被卷去的位置

function getScrollXY() {
  return document.body.scrollTop
    ? {
        x: document.body.scrollLeft,
        y: document.body.scrollTop
      }
    : {
        x: document.documentElement.scrollLeft,
        y: document.documentElement.scrollTop
      };
}

34 判断是否为数字类型

function isDigit(value) {var patrn = /^[0-9]*$/;
  if (patrn.exec(value) == null || value == "") {return false;} else {return true;}
}

35 检验 URL 链接是否有效

function getUrlState(URL) {var xmlhttp = new ActiveXObject("microsoft.xmlhttp");
  xmlhttp.Open("GET", URL, false);
  try {xmlhttp.Send();
  } catch (e) { } finally {
    var result = xmlhttp.responseText;
    if (result) {if (xmlhttp.Status == 200) {return true;} else {return false;}
    } else {return false;}
  }
}

36 获取 URL 上的参数

// 获取 URL 中的某参数值, 不区分大小写
// 获取 URL 中的某参数值, 不区分大小写,
// 默认是取 'hash' 里的参数,// 如果传其他参数支持取‘search’中的参数
// @param {String} name 参数名称
export function getUrlParam(name, type = "hash") {
  let newName = name,
    reg = new RegExp("(^|&)" + newName + "=([^&]*)(&|$)", "i"),
    paramHash = window.location.hash.split("?")[1] || "",
    paramSearch = window.location.search.split("?")[1] || "",
    param;
  type === "hash" ? (param = paramHash) : (param = paramSearch);
  let result = param.match(reg);
  if (result != null) {return result[2].split("/")[0];
  }
  return null;
}

37 获取窗体可见范围的宽与高

function getViewSize() {
  var de = document.documentElement;
  var db = document.body;
  var viewW = de.clientWidth == 0 ? db.clientWidth : de.clientWidth;
  var viewH = de.clientHeight == 0 ? db.clientHeight : de.clientHeight;
  return Array(viewW, viewH);
}

38 判断是否安卓移动设备访问

function isAndroidMobileDevice() {return /android/i.test(navigator.userAgent.toLowerCase());
}

39 判断是否苹果移动设备访问

function isAppleMobileDevice() {return /iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase());
}

40 是否是某类手机型号

// 用 devicePixelRatio 和分辨率判断
const isIphonex = () => {
  // X XS, XS Max, XR
  const xSeriesConfig = [
    {
      devicePixelRatio: 3,
      width: 375,
      height: 812
    },
    {
      devicePixelRatio: 3,
      width: 414,
      height: 896
    },
    {
      devicePixelRatio: 2,
      width: 414,
      height: 896
    }
  ];
  // h5
  if (typeof window !== "undefined" && window) {const isIOS = /iphone/gi.test(window.navigator.userAgent);
    if (!isIOS) return false;
    const {devicePixelRatio, screen} = window;
    const {width, height} = screen;
    return xSeriesConfig.some(item =>
        item.devicePixelRatio === devicePixelRatio &&
        item.width === width &&
        item.height === height
    );
  }
  return false;
};

    正文完
     0
    Yojack
    版权声明:本篇文章由 Yojack 于1970-01-01发表,共计5008字。
    转载说明:
    1 本网站名称:优杰开发笔记
    2 本站永久网址:https://yojack.cn
    3 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
    4 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    5 本站所有内容均可转载及分享, 但请注明出处
    6 我们始终尊重原创作者的版权,所有文章在发布时,均尽可能注明出处与作者。
    7 站长邮箱:laylwenl@gmail.com
    评论(没有评论)