<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
text-decoration: none;
color: #000;
font-size: 12px;
}
.news {
width: 190px;
height: 154px;
border-bottom: 1px solid #ccc;
background-color: #fff;
padding: 7px 13px 0;
box-sizing: border-box;
}
.news_t {
height: 19px;
border-bottom: 1px solid #ccc;
position: relative;
text-align: center;
}
.news_t a {
float: left;
height: 17px;
line-height: 17px;
width: 38px;
border-right: 1px solid #ccc;
}
.news_t div {
height: 2px;
width: 28px;
background-color: #f10215;
position: absolute;
bottom: -1px;
left: 4px;
}
.hide {
display: none;
}
.show {
display: block;
}
.newContainer {
padding-top: 10px;
}
.news_b {
padding-top: 15px;
}
</style>
</head>
<body>
<div class="news">
<div id="newsT" class="news_t">
<a href="#">促销</a>
<a href="#">公告</a>
<div id="flag"></div>
</div>
<!-- 详细内容 -->
<div id="newContainer">
<div class="news_b">
<li><a href="#">6折促销</a></li>
<li><a href="#">热卖商品</a></li>
</div>
<div class="news_b hide">
<li><a href="#">5折公告</a></li>
<li><a href="#">今日公告</a></li>
</div>
</div>
</div>
<script src="js/common.js"></script>
<script src="js/animate.js"></script>
<script>
// 获取元素
var newT = my$('newsT');
// 红色的线
var flag = my$('flag');
// 详细内容
var newContainer = my$('newContainer');
//1 获取到a标签注册事件
for (var i = 0; i < 2; i++) {
var link = newT.children[i];
link.onmouseenter = linkMouseenter;
// 设置a标签的自定义属性,记录索引(字符串类型)
link.setAttribute('index', i);
}
function linkMouseenter() {
// 让红色的线执行动画
// 获取当前触发事件的a标签的位置
var offsetLeft = this.offsetLeft;
animation(flag, offsetLeft + 4);
// 显示对应的详细内容
// 让所有的详细内容隐藏
for (var i = 0, len = newContainer.children.length; i < len; i++) { // 优化代码
var div = newContainer.children[i];
// 判断类样式中是否已经有hide
if (div.className.indexOf('hide') === -1) {
div.className = 'news_b hide';
}
}
// 当前对应的详细内容显示
var index = parseInt(this.getAttribute('index'));
newContainer.children[index].className = 'news_b show';
}
</script>
</body>
</html>
common.js:
// 通过id获取元素
function my$(element) {
var el = document.getElementById(element);
return el;
}
animate.js:
// 动画封装
// var timerId = null; // 需全局变量
function animation(element, target) {
// 给每个element增加一个属性timerId,保证定时器标志互不干扰
if (element.timerId) {
clearInterval(element.timerId);
element.timerId = null;
}
element.timerId = setInterval(function () {
// 步距
var step = 10;
var current = element.offsetLeft;
// 如果当前位置 > 目标位置 step < 0
if (current > target) {
step = -Math.abs(step);
}
// 当前位置和目标位置的差值小于step
// console.log(Math.abs(current - target));
// console.log(Math.abs(step));
if (Math.abs(current - target) <= Math.abs(step)) {
// 停止定时器
clearInterval(element.timerId);
element.style.left = target + 'px'; // 赋值为目标值
// 退出函数
return;
};
// 移动盒子
current += step;
element.style.left = current + 'px';
}, 30);
}