“新人”前端项目练习--01

151 阅读3分钟

前言

找了些新手练习项目,简单实现了下。 写的过程中暴露问题点还挺多,接下来就记录要复(预)习的点吧

1. expanding-cards

看效果图就感觉特别的陌生,第一反应是样式怎么写,写之前居然想用定位浮动写,磕磕碰碰写完后回过头再看。。嗯,还是好好学习吧。

exor4-n3noj.gif

html结构部分

内容一开始用的img图片做填充,并设定了图片宽高是父盒子的百分之百。后来发现里面的内容的宽高比是不会发生变化的,然后试了不设宽高,嗯,flex布局给结结实实的我上了一课。

所以改用了背景图属性。通过background-position: center;的方式将背景图固定到中间位置,无论容器怎么变化,背景图都会固定在中间位置,看上去更加的顺滑。

    <div class="card_container" id="card_container">
        <div class="single_card_body focus">
            <h3>Explore The World</h3>
        </div>
        <div class="single_card_body">
            <h3>Explore The World</h3>
        </div>
        <div class="single_card_body">
            <h3>Explore The World</h3>
        </div>
        <div class="single_card_body">
            <h3>Explore The World</h3>
        </div>
        <div class="single_card_body">
            <h3>Explore The World</h3>
        </div>
    </div>

</body>

<script src="./index.js"></script>

css

父盒子用了flex做布局,样式会自动计算子盒子的位置。子盒子上的flex属性由是flex-grow,flex-shrink和flex-basis三个属性的缩写,当flex取值为一个数字,则该数字是设置的flex-grow值,其它两个属性用初始值,如flex: 0.5时,等同于flex: 0.5 1 0%。即:

flex-grow:0.5;
flex-shrink:1;
flex-basis:0%;

flex-grow项在 flex 容器中分配剩余空间的相对比例。剩余空间是 flex 容器的大小减去所有 flex 项的大小加起来的大小。如果所有的兄弟项目都有相同的 flex-grow 系数,那么所有的项目将剩余空间按相同比例分配,否则将根据不同的 flex-grow 定义的比例进行分配。

当flex由0.5变为5后,这个盒子的相对比例就变大了;相对的,其他盒子的相对比例就会变少,就可以实现效果中的“一个变大,其他变小”的动态效果。

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
}
.card_container {
    display: flex;
    width: 90vw;
}
.single_card_body {
    height: 90vh;
    flex: 0.5;
    margin: 10px;
    position: relative;
    background-image: url('https://images.unsplash.com/photo-1558979158-65a1eaa08691?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    border-radius: 50px;
    cursor: pointer;
    color: #ffffff;
    transition: all 700ms ease-in;
    -webkit-transition: all 700ms ease-in;
}

.single_card_body.focus{
    flex: 5;
}

js

js逻辑涉及到事件委托和排他思想的实现、事件冒泡、以及伪数组HTMLCollection使用数组方法的实现。(看到在调试窗看到HTMLCollection和NodeList时候真就唤起了一部分过去的记忆 OvO)

function removeClassName(cards){
     Array.prototype.forEach.call(cards,element => {
        element.classList.remove('focus')
    });
}
let body=document.getElementById('card_container'),
    cards=body.children
body.addEventListener('click',function(eve){
    eve.stopPropagation();
    removeClassName(cards)
    let target= eve.target
    target.classList.add('focus')
})

结语

很简单的一个小项目,但是涉及到的东西其实挺多的,尤其是象我这种因为兼容问题不敢用新属性的人,像是flex布局,真是很久没写过,简直手生之极。

同时也复习到一些有意思的东西,像是伪数组类数组向真实数组的转化、css中一些不常用的单位,vw,vh这些,还复习了事件冒泡和默认点击行为。顺便摸鱼又去复刷了几篇文章,今天属实赚到了,哈哈。

3fgrs-ze38v.gif