JavaScript practice case: super simple and cool picture accordion effect

The accordion effect is very popular, and the content can be expanded and contracted at will, which is very beautiful.

Special effects requirements

Move the mouse to the picture, the current picture will zoom in, and other pictures will shrink.

HTML

<div class="pics">
    <ul id="picList">
        <li><a href="#"><img src="images/pic1.jpg" alt=""></a></li>
        <li><a href="#"><img src="images/pic2.jpg" alt=""></a></li>
        <li><a href="#"><img src="images/pic3.jpg" alt=""></a></li>
        <li><a href="#"><img src="images/pic4.jpg" alt=""></a></li>
        <li><a href="#"><img src="images/pic5.jpg" alt=""></a></li>
    </ul>
</div>

CSS

*{
    margin: 0;
    padding: 0;
}
ul,li,ol{
    list-style: none;
}
img{
    border:none;
}
/* 公用css 结束 */

.pics{
    width: 1000px; /* 1个 600px,4个 100px*/
    margin-left: auto;
    margin-right: auto;
    height: 400px;
    overflow: hidden;
}
.pics ul{
    display: flex;    /* flex 布局让 li 横向排列 */
    justify-content: space-between;  /* 内容靠向两端 */
}
.pics ul li{
    width: 100px;
    height: 400px;
    position: relative;
    overflow: hidden;
    transition:all 0.4s;   /* 过渡动画 */
    flex-grow: 1;   /* 让 li 始终能占满整个 ul ,保证变化过程中 li 之间没有缝隙 */
}
.pics ul li img{
    position: absolute;   /* 确保图片在 li 里显示中间部分 */
    left:50%;
    top:0;
    margin-left: -300px;
}
.pics ul li.active{    /* 有类 active li 宽度为 600px。去掉,就会恢复 100px */
    width: 600px;
}

Several details need attention:

  1. li's widening and narrowing animations are all completed by CSS3 transition
  2. In order to prevent a gap between li during the change of li, li adds a style:
 flex-grow: 1; 

Let li automatically fill ul.

     3. In order to keep the picture always centered in li, absolute positioning is applied to the picture. li is relative positioning.

.pics ul li img{
    position: absolute;
    left:50%;
    top:0;
    margin-left: -300px;
}

JavaScript

let ul = document.getElementById("picList");
let lies = ul.children ;
// 第一个 li 变宽:增加类 active
lies[0].classList.add("active");
// 查找兄弟标签函数
let findSiblings = function(tag){
    let parent = tag.parentNode ;
    let child = parent.children ;
    let sb = [];
    for(let i = 0 ; i <= child.length-1 ; i++ ){
        if( tag !== child[i]){
            sb.push( child[i]);
        }
    }
    return sb ;
};

for( let i = 0 ; i <= lies.length-1 ; i++  ){
    lies[i].addEventListener("mouseenter",function(){
        let siblings = findSiblings(this);
        // 当前标签变宽: 增加类 active
        this.classList.add("active");
        // 兄弟标签变窄
        for(let k = 0 ; k <= siblings.length-1 ; k++ ){
            // 兄弟标签去掉 active
            siblings[k].classList.remove("active");
        }
    });
}

Finished~! !

Guess you like

Origin blog.csdn.net/weixin_42703239/article/details/108158826