web前端自学之路

web前端 -- Day21 js基础

2019-03-26  本文已影响0人  韩发发吖

元素移动

元素要实现移动,就要要脱离文档流 ,设置样式 position: absolute;
注意问题

  1. 如果样式的代码是在style标签中设置,外边是获取不到的。
  2. 如果样式的代码是在style属性中设置的 ,外边是可以获取的。

动画函数封装代码:

function animate(element, target) {
clearInterval(element.timeId);
//定时器的id值存储到对象的一个属性中
element.timeId = setInterval(function () {
  //获取元素的当前的位置,数字类型
  var current = element.offsetLeft;
  //每次移动的距离
  var step = 10;
  step = current < target ? step : -step;
  //当前移动到位置
  current += step;
  if (Math.abs(current - target) > Math.abs(step)) {
    element.style.left = current + "px";
  } else {
    //清理定时器
    clearInterval(element.timeId);
    //直接到达目标
    element.style.left = target + "px";
  }
}, 20);
}  

以后获取元素的宽高,应该使用offset系列来获取
offsetWidth:获取元素的宽
offsetHeight:获取元素的高
offsetTop: 获取元素距离上边位置的值
offsetLeft: 获取元素距离左边位置的值

console.log(my$("dv1").offsetWidth);
console.log(my$("dv1").offsetHeight);
console.log(my$("dv1").offsetTop);
console.log(my$("dv1").offsetLeft);

没有脱离文档流: offsetLeft:父级元素的margin+父级元素padding+父级元素的border

脱离文档流: 主要是自己的left和自己的margin

直接通过document获取元素

// 获取body
console.log("获取的是元素 -- 标签",document.body); 
// 获取title
console.log("获取的是标签中的值",document.title); 
document.title = "你瞅啥!!!";
console.log("获取的是HTML",document.documentElement);

图片跟着鼠标移动

这里注意要设置img的样式:position: absolute;

// 图片跟着鼠标移动
document.onmousemove = function(e){
    console.log("鼠标的事件",e);
    // clientX:可是区域的横坐标
    // clientY:可是区域的纵坐标
    my$("im").style.left = e.clientX+"px";
    my$("im").style.top = e.clientY+"px";
}
上一篇 下一篇

猜你喜欢

热点阅读