编程语言
首页 > 编程语言> > JavaScript+CSS+HTML 编写手风琴效果

JavaScript+CSS+HTML 编写手风琴效果

作者:互联网

效果图:

 可以通过 https://littlehiuman.github.io/Accordion.html 查看效果。

 代码如下:

* {
  margin: 0;
  padding: 0;
}

.container {
  position: relative;
  width: 520px;
  height: 400px;
  overflow: hidden;
}

.wrapper {
  position: absolute;
  height: 100%;
  top: 0;
  overflow: hidden;
}

.inner {
  display: block;
  width: 100%;
  height: 100%;
}

.title {
  position: absolute;
  width: 100%;
  height: 30px;
  line-height: 30px;
  text-align: center;
  color: #fff;
  background-color: rgba(0, 0, 0, .5);
  left: 0;
  bottom: 0;
}
<div class="container">
  <div class="wrapper">
    <div class="title">这是标题1</div>
    <img class="inner" src="http://a.hiphotos.baidu.com/zhidao/pic/item/7c1ed21b0ef41bd5a5ea166a53da81cb38db3df6.jpg"
      alt="">
  </div>
  <div class="wrapper">
    <div class="title">这是标题2</div>
    <img class="inner" src="http://e.hiphotos.baidu.com/zhidao/pic/item/9d82d158ccbf6c81ec5127f8bc3eb13533fa40bf.jpg"
      alt="">
  </div>
  <div class="wrapper">
    <div class="title">这是标题3</div>
    <img class="inner" src="http://dl.ppt123.net/pptbj/201603/2016030410213428.jpg" alt="">
  </div>
  <div class="wrapper">
    <div class="title">这是标题4</div>
    <img class="inner" src="http://1824.img.pp.sohu.com.cn/images/2008/6/5/13/17/11af6fc767c.jpg" alt="">
  </div>
  <div class="wrapper">
    <div class="title">这是标题5</div>
    <img class="inner" src="http://pic1.win4000.com/wallpaper/3/53ad42e6acb5d.jpg" alt="">
  </div>
</div>
// 各容器
var container = document.getElementsByClassName('container')[0];
var wrappers = document.getElementsByClassName('wrapper');
var inners = document.getElementsByClassName('inner');
// 设定宽高
var width = 520;
var height = container.getBoundingClientRect().height;
var eachWidth = width / wrappers.length;
container.style.width = (width + eachWidth * (wrappers.length - 1)) + 'px';
// 设定索引
var index = 0;
// 给图片加宽度以及给容器添加鼠标事件
init();
// 修改容器的left和width
loadImg();
// 函数
function init() {
  for (var i = 0; i < wrappers.length; i++) {
    inners[i].style.width = width + 'px';
    wrappers[i]['data-index'] = i;
    wrappers[i].onmouseenter = function () {
      if (index === this['data-index']) return;
      index = this['data-index'];
      loadImg();
    }
  }
}
function loadImg() {
  for (var i = 0; i < wrappers.length; i++) {
    wrappers[i].style.width = i == index ? width + 'px' : eachWidth + 'px';
    wrappers[i].style.left = i > index ? (width + eachWidth * (i - 1)) + 'px' : (eachWidth * i) + 'px';
  }
}

标签:wrappers,index,px,JavaScript,height,width,HTML,var,CSS
来源: https://www.cnblogs.com/hiuman/p/12189608.html