JS基本功系列-DOM里面常见的几种封装小结

admin 2022年5月8日18:12:52评论19 views字数 6180阅读20分36秒阅读模式

前言

注意:这几个封装一定要练习的非常熟练

遍历一个父元素的子元素节点

//遍历一个父元素的子元素节点
Element.prototype.elemChildren = function (index{
  var childNodes = this.childNodes,
    len = childNodes.length,
    item;
  var temp = {
    'length'0,
    'push'Array.prototype.push,
    'splice'Array.prototype.splice
  };
  for (let i = 0; i < len; i++) {
    item = childNodes[i];

    if (item.nodeType === 1) {
      temp.push(item)
    }
  }

  if (index !== undefined && typeof (index) !== 'number') {//存在且不为number类型,就是string类型
    return undefined;
  }
  return index === undefined ? temp : temp[index];
}

遍历一个节点的所有子节点,包含孙子节点

function getFullchildren(node{
  var children = node.children,
    len = children.length,
    item;
  if (node && node.nodeType === 1) {
    console.log(node);
  }

  for (var i = 0; i < len; i++) {
    item = children[i];

    if (item.nodeType === 1) {
      getFullchildren(item)
    }
  }
}

在原型上面写一个元素的第N层父级元素

Element.prototype.elemParent = function (n{
  var type = typeof n,
    elem = this;
  if (type === 'undefined' || type !== "number") {
    return elem.parentNode;
  } else if (n < 0) {
    return undefined;
  }

  while (n) {
    if (elem.nodeName === 'HTML') {
      elem = null
      return elem
    }
    elem = elem.parentNode;
    n--;
  }
  return elem;
}

寻找兄弟节点


<div>
  <p>p标签</p>
  <h1>h1标签</h1>
  <a href="">超级链接</a>
  <strong>strong</strong>
  <em>em</em>
  <h2>h2</h2>
</div
  var a = document.getElementsByTagName('a')[0];
Element.prototype.elemParent = function (n{
  var type = typeof (n),
    elem = this;

  if (type === 'undefined' || type !== 'number') {
    return elem.parentNode;
  } else if (n < 0) {
    return undefined
  }


  while (n) {
    if (elem.nodeName === 'HTML') {
      elem = null
      return elem
    }
    elem = elem.parentNode;
    n--;
  }
  return elem
}

console.log(a.elemParent(3))

元素逆序


<div>
  <h1>11111</h1>
  <a href="">22222</a>
  <p>333333</p>
  <strong>44444</strong>
  <ul>
    <li>999</li>
  </ul>
  <ul>
    <li>99909</li>
  </ul>
</div>
//div是包裹我们想要逆序节点的节点
var div = document.getElementsByTagName('div')[0],
  children = div.childNodes,
  len = children.length;


while (len--) {
  console.log(children[len]);
  div.appendChild(children[len]);
}

时钟


<div>
  <p></p>
</div>
var p = document.getElementsByTagName('p')[0];

setInterval(function ({
  p.innerHTML = new Date().getDateTime();
}, 1000)

Date.prototype.getDateTime = function ({
  var year = this.getFullYear(),
    month = this.getMonth() + 1,
    day = this.getDate(),
    hours = this.getHours(),
    minutes = this.getMinutes(),
    seconds = this.getSeconds();

  function setZero(num{
    if (num < 10) {
      num = '0' + num;
    }
    return num;
  }

  return year + '-' + setZero(month) + '-' + setZero(day) + ' ' + setZero(hours) +
    ':' + setZero(minutes) + ':' + setZero(seconds);
}

倒计时

 var oPara = document.getElementsByTagName('p')[0],
  endTime = new Date(2022515235959).getTime(),
  t = null;

t = setInterval(function ({
  oPara.innerHTML = new Date().countDown(endTime, t);
}, 1000)

Date.prototype.countDown = function (endTime, timer{
  var nowTime = this.getTime(),
    lefTime = (endTime - nowTime) / 1000,
    d, h, m, s;

  if (lefTime >= 0) {
    d = Math.floor(lefTime / 60 / 60 / 24);
    h = Math.floor(lefTime / 60 / 60 % 24);
    m = Math.floor(lefTime / 60 % 60);
    s = Math.floor(lefTime % 60);
  } else {
    clearInterval(timer)
  }

  return d + '天' + h + '时' + m + '分钟' + s + '秒';
}


// Math.round(-5.3)//-5
// Math.round(-5.5)//-5
// Math.round(-5.6)//-6
// Math.round(5.5)//6

查看滚动条的距离

//封装的是滚动条的位移
//封装滚动条,考虑到兼容性了,很重要!下面是企业的写法
function getScrollOffset({
  if (window.pageXOffset) {
    return {
      leftwindow.pageXOffset,
      topwindow.pageYOffset
    }
  } else {
    return {
      leftdocument.body.scrollLeft + document.documentElement.scrollLeft,
      //两者一般只有一个有效,故写为加法
      topdocument.body.scrollTop + document.documentElement.scrollTop
    }
  }
}

封装可视窗口

  //下面是考虑过兼容性之后的封装可视窗口
function getViewportSize({
  if (window.innerWidth) {
    return {
      widthwindow.innerWidth,
      heightwindow.innerHeight,
    }
  } else {
    if (document.compatMode === "BackCompat") {
      return {
        widthdocument.body.clientWidth,
        heightdocument.body.clientHeight
      }
    } else {
      return {
        widthdocument.documentElement.clientWidth,
        heightdocument.documentElement.clientHeight
      }
    }
  }
}

getViewportSize();

封装html文档的高度和宽度

//封装html文档的高度和宽度
function getScrollSize({
  if (document.body.scrollWidth) {
    return {
      widthdocument.body.scrollWidth,
      heightdocument.body.scrollHeight
    }
  } else {
    return {
      widthdocument.documentElement.scrollWidth,
      heightdocument.documentElement.scrollHeight
    }
  }
}

getScrollSize()

获取元素距离窗口左上角的位置距离


<style>
  body {
    margin0;
  }

  .grandPa {
    position: absolute;
    top100px;
    left100px;
    width360px;
    height360px;
    background-color#ccc;
  }

  .parent {
    position: absolute;
    top30px;
    left30px;
    width300px;
    height300px;
    background-color#999;
    overflow: hidden;
  }

  .son {
    position: absolute;
    top100px;
    left100px;
    width100px;
    height100px;
    background-color#00FF00;
  }
</style>

<div class="grandPa">
  <div class="parent">
    <div class="son">
    </div>
  </div>
</div>
 // 获取元素距离窗口左上角的位置距离
var son = document.getElementsByClassName('son')[0];

// 获取元素距离窗口左上角的位置距离
function getElemToDocPosition(el{
  var parent = el.offsetParent,
    offsetLeft = el.offsetLeft,
    offsetTop = el.offsetTop;

  while (parent) {
    offsetLeft += parent.offsetLeft;
    offsetTop += parent.offsetTop;
    parent = parent.offsetParent;
  }

  return {
    left: offsetLeft,
    top: offsetTop
  }

}

getElemToDocPosition(son);

获取元素的样式属性

// 查看css属性的方法
//   elem.style 里面有CSSStyleDeclaration属性
// 查看计算样式,常规:
// window.getComputeStyle(elem, null)[prop];
//   window.getComputeStyle(elem, null).prop;
//   E8 及以下:
// elem.currentStyle
//获取元素的样式属性====>兼容了不同的浏览器
function getStyles(el, prop{
  if (window.getComputedStyle) {
    if (prop) {
      return parseInt(window.getComputedStyle(el, null)[prop]);
    } else {
      return window.getComputedStyle(el, null);
    }
  } else {
    if (prop) {
      return parseInt(el.currentStyle[prop]);
    } else {
      return el.currentStyle;
    }
  }
}

getStyles(oDiv, 'height')


原文始发于微信公众号(迪哥讲事):JS基本功系列-DOM里面常见的几种封装小结

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2022年5月8日18:12:52
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   JS基本功系列-DOM里面常见的几种封装小结https://cn-sec.com/archives/974755.html

发表评论

匿名网友 填写信息