练习地址:http://www.fgm.cc/learn/lesson2/09.html
实现思路:
- 下拉三角形通过border来画:div宽高设为0,border值设大点,保留三角形底边那边的边框的颜色,其他颜色设为transparent。transparent是全透明黑色(black)的速记法,即一个类似rgba(0,0,0,0)这样的值。具体可看这篇:CSS绘制三角形——border法。
- 设置两个三角形div,他们的位置一样,点击修改display为none或block实现两者之间的显示与隐藏
- 下面的list用flex布局实现,具体可看这篇:Flex布局。很有用的布局方式!要学!
代码如下:
HTML
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>单一按钮显示/隐藏</title>
<link rel="stylesheet" type="text/css" href="9_triangle.css">
</head>
<body>
<div id="container">
<div id="list">
播放列表
<div id="triangle1"></div>
<div id="triangle2"></div>
</div>
<ul>
<li>你还要我怎样-薛之谦</li>
<li>修炼爱情-林俊杰</li>
<li>等你下课-周杰伦</li>
<li>我不愿让你一个人-五月天</li>
<li>消愁-毛不易</li>
<li>水星记-郭顶</li>
</ul>
</div>
<script type="text/javascript" src="9_triangle.js"></script>
</body>
</html>
css
#container {
width: 200px;
margin: 0 auto;
background: #FFCC33;
color: #996600;
font-size: 14px;
border: 1px solid #FF9933;
}
#list {
width: 179px;
background: #FF9933;
margin: 0;
padding: 6px;
padding-left: 13px;
border: 1px solid #FFFFCC;
}
ul {
margin: 0;
padding: 0;
/*position: relative;
top: 7px;*/
display: flex;
flex-direction: column;
}
li {
list-style-type: none;
padding: 4px 8px;
}
li:hover {
text-decoration: underline;
background: #FFFFCC;
}
#triangle1 {
/*display: none;*/
float: right;
margin: 5px 5px 0;
width: 0;
height: 0;
border: 8px solid;
border-color: #CC9933 transparent transparent;
}
#triangle2 {
float: right;
margin: -4px 5px 0;
width: 0;
height: 0;
border: 8px solid;
border-color: transparent transparent #CC9933;
display: none;
}
JavaScript
window.onload = function() {
var tri1 = document.getElementById("triangle1");
var tri2 = document.getElementById("triangle2");
var list = document.getElementsByTagName("ul")[0];
tri1.onclick = function() {
list.style.display = "none";
tri2.style.display = "block";
tri1.style.display = "none";
}
tri2.onclick = function() {
list.style.display = "block";
tri1.style.display = "block";
tri2.style.display = "none";
}
}
我觉得可能写得有点累赘,应该有更简洁的代码。欢迎指点迷津,谢谢朋友们!