js网页特效(一)

1.offset系列

相关属性:

  1. offsetWidth //可视区域区域的
  2. offsetHeith //可视区域的高
  3. offsetTop //从border开始计算
  4. offsetLeft //从border开始计算
  5. offsetParent//距离自身最近的带有定位的父级
    //如果父级没定位 继续往上找 找到body为止

详解:

offsetParent爸爸去哪

  1. 返回该对象距离最近的带有定位的父级

  2. 如果当前元素的所有父级元素都没有定位(position为absolute或relative),
    offsetParent为body

  3. 如果当前元素的父级元素中有定位(position为absolute或relative),
    offsetParent取最近的那个父级元素

  4. 另外注意offsetParent与parentNode的区别parentNode只找自己的上一级(亲爹)

offsetHeight与offsetWidth的构成:

    offsetHeight = height+padding+border
    注意: 包括 自身高度 内边距 边框 不包括 外边距
    offsetWidth = Width+padding+border
    注意: 包括 自身高度 内边距 边框 不包括 外边距

offsetWidth和style.width的区别:

demo.style.height只能获取行内样式,如果样式写到了其他地方,
甚至根本就没写,便无法获取

style.height是字符串(而且带单位),offsetHeight是数值

demo.style.height可以设置行内样式,offsetHeight是只读属性

offsetLeft和style.left的区别

一、style.left只能获取行内样式

二、offsetLeft只读,style.left可读可写

三、offsetLeft是数值,style.left是字符串并且有单位px

四、如果没有加定位,style.left获取的数值可能是无效的

五、最大区别在于offsetLeft以border左上角为基准,style.left以margin左上角为基准

注意:在编写 匀速运动时,要注意margin带来的负面影响。

2.Math()对象

Math对象常用方法:

天花板 向上取整 负数取更大的

  1. Math.ceil(x)

地板 向下取整 负数取更小的

  1. Math.floor(x)

//四舍五入

3.Math.round(x)

取绝对值

4.Math.abs(x)

注意:

 Math.round(-1.5)  等于-1
 Math.round(1.5)  等于-2

3.动画原理

1. 动画原理公式

动画原理公式: leader = leader + step

解释:

leader表示盒子当前位置
step表示步长(相当于速度)
box.style.left = box.offsetLeft + 10 + "px";
让setInterval不断执行某个函数修改盒子的位置属性最后就实现了动画的效果

2.动画函数封装源码:

function animate(obj, target) {
    clearInterval(obj.timer);
    obj.timer = setInterval(function () {
        //leader = leader + step
        var leader = obj.offsetLeft;
        //target-leader
        var step = 10;
        var step = (target - leader) > 0 ? step : -step;
        //
        if (Math.abs(target - leader) > Math.abs(step)) {
            leader = leader + step;
            obj.style.left = leader + "px";
        } else {
            obj.style.left = target + "px";
            clearInterval(obj.timer);
        }
    }, 15)
}

你可能感兴趣的:(js网页特效(一))