Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@TTT00x

画像をランダムで表示させる

More than 3 years have passed since last update.

仕様

ロードの度に表示される画像がランダムで切り替わるようにしたい。

js

js
var randomImg = function () {
    var $target = $('[data-randomimg]'),
        //表示させたい画像の個数を配列に入れる
        ary = [1,2,3], 
        //ランダムで配列内の数字を取得
        i = ary[Math.floor(Math.random() * ary.length)],
        src;
    if(!$target.length) return;
    src = 'img/img_' + i + '.gif';
    $target.attr('src',src);
};

$(function () {
    randomImg();
});

まとめ

わざわざ配列に画像の個数を入れるのがなんとも。

0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
TTT00x
エンジニア見習い
howtelevision
グローバルプロフェッショナルを目指す学生に向けた国内最大級の就職活動サイト「外資就活ドットコム」を運営

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?