Skip to content

Latest commit

 

History

History
167 lines (125 loc) · 4.42 KB

File metadata and controls

167 lines (125 loc) · 4.42 KB

判断滚动条的方向


document.body.scrollTop  // 顶部距离
document.documentElement.scrollTop  // firefox
dom.offsetTop  // 顶部距离(某一元素)
document.documentElement.clientHeight  // 当前高度
document.documentElement.scrollHeight  // 完整高度

function getScrool() {
	var timeScroll = null
	var current = document.body.scrollTop
	window.onscroll = function() {
		clearTimeout(timeScroll)
		timeScroll =  setTimeout(function(){
			judge()  // 调用滚动方向判断函数
			lazyLoad()  // 调用懒加载
		},100)
	}
	function judge() {
		if(current-document.body.scrollTop>0){
			console.log('up')
		}
		else{
			console.log('down')
		}
		current = document.body.scrollTop
	}
}

参考

懒加载实现

把图片的地址存在自定义的data属性里,根据鼠标是否滚动到图片的位置,动态把data里的URL赋值给src属性。图片标签获得了src属性就会触发一个get请求,加载图片。


var image = {
  length: document.images.length,
  linkAll: document.images,
  linkIdCurrent: 0
}
function lazyLoad () {
  var bodyScrollTop = document.body.scrollTop
  var clientHeight = document.documentElement.clientHeight
  if ( image.linkIdCurrent < image.length ) {
    var currentScrollTop = image.linkAll[image.linkIdCurrent].offsetTop
    if ( currentScrollTop <= bodyScrollTop + clientHeight ) {
      var imgSrc = image.linkAll[image.linkIdCurrent].getAttribute('data-src')
      image.linkAll[image.linkIdCurrent].src = imgSrc
      image.linkAll[image.linkIdCurrent].removeAttribute('data-src')
      image.linkIdCurrent++
      lazyLoad()
    }
  }
}
lazyLoad()

参考

文档模型


节点操作

createElement(name)  // 创建节点
appendChild(node)  // 添加节点
removeChild(node)  // 删除节点
dom.childNodes  // 节点列表

参考

等高布局


.parent {
  position: relative;  /* 相对布局 */
  height: 300px;
}
.parent * {
  position: absolute;  /* 和父元素的相对布局配合,可以使子元素基于父元素定位 */
  width: 200px;
  /* 设置顶部和底部都为0,等高布局形成 */
  top: 0;
  bottom: 0;
}

参考

清除浮动和BFC

属性操作


body.attributes  // 返回属性列表
getAttribute(name)  // 获取
setAttribute(name, value)  // 设置
removeAttribute(name)  // 删除

媒体查询的两种插入方式


@media only screen and (max-width:767px) {...}
<style media="only screen and (max-width:767px)">...</style>

参考

格式化JS对象成JSON


var obj = {
  a: 1,
  b: 2
}
var res = JSON.stringify(obj, null, '  ')
console.log(res)
/* 结果
"{
  "a": 1,
  "b": 2
 }"
*/