4
1

More than 1 year has passed since last update.

HTML/CSS Javascriptでボタンを作ってみた

Posted at

初めに 

ボタンを作るきっかけは、Googleの「I’m feeling」が、きっかけでした。
「I`m feeling」にカーソルを合わせると、ボタンの中身がスロットのように
回転してランダムに文字が出てくるのが、とても面白いと思いました。
今回制作したボタンは、スロットのように回転しませんが、マウスカーソルを合わせると、
ランダムに文字が出てくる仕組みです。

ボタン作成

1 ボタンの中身がランダムに変化する

ボタンの中身の文字を変化させるために、あらかじめjavascriptで文字列のリストを記述
します。そしてlist[Math.floor(Math.random()*list.length)]を変数aに代入して、
ランダムに文字が出てくるようにします。

button.js
const list = ["eat double cheese burger", "driving a car", "go and see messi", "crush my car"];

let a = list[Math.floor(Math.random()*list.length)];

2 カーソルを合わせた時の動き

ここでは、マウスのカーソルを合わせた時の動作をmouseoverとmouseleaveを記述して、
合わせた時、話した時の別々の処理を書きます。

button.js
const target = document.getElementById('button');


    

    target.addEventListener("mouseover", () => {  //マウスのカーソルを合わせた時
        document.getElementById("button").textContent = a;//先述のリストの中の文字列をランダムに表示
        

    }, false);
    
    target.addEventListener("mouseleave", () => {// マウスカーソルを離した時
        document.getElementById("button").textContent = "I wanna....";//元の文字列「I wanna ....」を表示
        

    }, false);

}

最後に

次回はgoogleの「I'm feeling」に近づけるよう、スロットのような効果の作成に挑戦してみたいです。

See the Pen I wanna.... by tsubasa (@tsubasamaru) on CodePen.

4
1
1

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
4
1