4-20

今天了解了哈offset这个东西

用途:方便获取元素大小

 

这网上的图,有点乱,大概的还是可以理解的

1.offWidth,offHeight:主要的到对象的宽度和高度

2/offsetLeft 和 offsetTop:就是子盒子到定位的父盒子边框到边框的距离

..........

 

理解还是差不多,然后试着着弄了个弹性导航,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>弹性导航</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}

#nav {
width: 900px;
height: 80px;
background-color: royalblue;
margin: 100px auto;
position: relative;
}

#nav ul {
position: relative;
}

#nav ul li {
width: 90px;
height: 80px;
float: left;
text-align: center;
line-height: 80px;
cursor: pointer;
}

#nav #move {
width: 90px;
height: 80px;
background-color: sandybrown;
position: absolute;
display: block;
}
</style>
</head>
<body>
<div id="nav">
<span id="move"></span>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
</div>
<script>
window.onload = function () {
//1.获取需要的标签
var nav = document.getElementById("nav");
var move = document.getElementById("move");
var ul = document.getElementsByTagName("ul");
var allLis = document.getElementsByTagName("li");

//记录鼠标点击的位置
var beginX = 0;

//2.遍历
for (var i = 0; i < allLis.length; i++) {
var li = allLis[i];

//2.1监听鼠标进入
li.onmouseover = function () {
end = this.offsetLeft;
};

//2.2监听鼠标按下事件
li.onmousedown = function () {
beginX = this.offsetLeft
};

//2.3监听鼠标离开事件
li.onmouseout = function () {
end = beginX;
};
}

//3.动画效果
var begin = 0, end = 0;
setInterval(function () {
begin = begin + (end - begin) * 0.01;
move.style.left = begin + 'px';
}, 10)
}
</script>
</body>
</html>
posted @ 2019-04-20 22:07  不要呀  阅读(172)  评论(0)    收藏  举报