LoginSignup
3
1

More than 5 years have passed since last update.

jQueryを知らなくてもHTMLで登場アニメーション

Last updated at Posted at 2018-07-07

今回はサイトで使えるように
誰でも簡単に出現アニメーションをつけれるように作ってみました。

divでもaタグでも何でも使えます。

注意点 "marginが消えます。"

y93ta-z9ng2.gif

使い方

css
body {
    overflow-x: hidden;
}
[vector="left"]{
    opacity: 0;
    margin-left: 1000px;
}
[vector="right"]{
    opacity: 0;
    margin-right: 1000px;
}
[vector="top"]{
    opacity: 0;
    margin-top: 1000px;
}
[vector="bottom"]{
    opacity: 0;
    margin-bottom: 1000px;
}
html
<h2 class="anim" type="linear" time="1000" vector="left">左へ 1</h2>
<h2 class="anim" type="linear" time="2000" vector="left">左へ 2</h2>
<h2 class="anim" type="swing" time="4000" vector="left">左へ 3</h2>
<h2 class="anim" type="linear" time="1000" vector="right">右へ</h2>
<h2 class="anim" type="linear" time="3000" vector="top">出現</h2>

まずclassに anim を追加します。

typeは linearswing の2つがあります
これらの違いは、linearは一定速度で動くのに対して
swingは真ん中辺りが一番早くなり、最初と最後は緩やかになります。
振り子みたいなものです

timeはアニメーションが終了するまでの時間を
1000 / 1秒 で指定できます。
つまり4000を指定すると 4秒間アニメーションします。

vectorは加える方向を指定します。
まあ移動させたい向きを指定してください。

JavaScriptのソースを貼ります
くそソースだけどゆるちて

javascript
$(window).on("scroll", function(){
    $('.anim').each(function(){
        let elem = $(this);
        let anim_type = elem.attr("type");
        let anim_time = elem.attr("time");
        let anim_vector = elem.attr("vector");
        if(isScrolledIntoView(this)){
            async function anim(){
                await animate(elem, anim_vector, anim_time, anim_type);
            }
            anim();
        }
    });
});
async function animate(elem, anim_vector, anim_time, anim_type){
    let vec = "margin-" + anim_vector;
    elem.animate({
        opacity: 1,
        [vec]: "0px"
    }, {
        duration: Number(anim_time),
        easing: anim_type
    });
}
function isScrolledIntoView(elem){
    try {
        let docViewTop = $(window).scrollTop();
        let docViewBottom = docViewTop + $(window).height();
        let elemTop = $(elem).offset().top;
        let elemBottom = elemTop + $(elem).height();
        return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    } catch(error) {
        console.log(error);
    }
}
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1