• ベストアンサー

画像がフェードイン・アウトするクラスの作り方教えて..

前置き:別に困っているわけでもありません ・こんな質問許されないかも(ご容赦を) ・自分で勉強しろと言われるかも(ごもっとも) ・ごみプログラムがさらにごみプログラムを生んでいるかも(ごめんなさい) 本題: いつぞやのタイトルくるくるのサンプルを基に、画像がフェードイン、 フェードアウトするオブジェクト指向っぽいスクリプトを作りました。 下のソースです。スタイル属性の変更をwindow.setIntervalを使って counter値に達するまでループ実行しているだけです。 似たような処理のfadeinクラスとfadeoutクラスを作って、  fadein.start(ターゲット,インターバルミリ秒);  fadeout.start(ターゲット,インターバルミリ秒); でフェードイン、フェードアウトを開始していますが、 fadeinクラスとfadeoutクラスをfadeinoutクラス一つにまとめちゃって、 fadeinoutクラスのメソッド(?)としてfadein、fadeoutを使えるように するには、どうやって作ればよいのかと言うのが質問です。 本当は、  var myobj = new fadeinout(ターゲット,インターバルミリ秒); とインスタンスして  myobj.fadein;  myobj.fadeout; みたく使うためのコーディングがよくわからんのです。 抜本的に書き換えた方がよいのでしょうか... <作ったサンプル> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="ja-JP"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="Content-Script-Type" content="text/javascript"> <title>FadeIn/FadeOut</title> <style type="text/css"></style> <script type="text/javascript" charset="utf-8"> <!-- var fadein = function (node,interval){ this.counter = 0; this.target = node; this.interval = interval; this.timerId = setInterval((function(that){ return function(){that.loop();}; })(this),this.interval); this.stop = function () { this.timerId && clearInterval(this.timerId); this.timerId = null; }; this.loop = function(){ this.target.style.width=this.counter+"px"; this.target.style.height=this.counter+"px"; this.target.style.opacity = this.counter / 100; this.target.style.filter = "alpha(opacity=" + this.counter + ")"; if( ++this.counter>100) this.stop(); }; }; var fadeout = function (node,interval){ this.counter = 100; this.target = node; this.interval = interval; this.timerId = setInterval((function(that){ return function(){that.loop();}; })(this),this.interval); this.stop = function () { this.timerId && clearInterval(this.timerId); this.timerId = null; }; this.loop = function(){ this.target.style.width=this.counter+"px"; this.target.style.height=this.counter+"px"; this.target.style.opacity = this.counter / 100; this.target.style.filter = "alpha(opacity=" + this.counter + ")"; if( --this.counter<0) this.stop(); }; }; fadein.start = function(target,interval){ new fadein(target,interval ); } fadeout.start = function(target,interval){ new fadeout(target,interval ); } function fadein_s(){ var target=document.getElementById("target"); fadein.start(target,1); } function fadeout_s(){ var target=document.getElementById("target"); fadeout.start(target,1); } // --> </script> </head> <body> <div> <image id="target" src="image/yahagi.png" style="width:0px;height:0px;"> </div> <button onclick="fadein_s();">フェードイン</button> <button onclick="fadeout_s();">フェードアウト</button> </body> </html>

質問者が選んだベストアンサー

  • ベストアンサー
回答No.6

追記。 オブジェクト指向的なプログラムは、いまだに良くわかりません。 勉強になったコードを思い返せば、一つの機能は、1つだけにし、 再利用しやすい形で、細分化されて、それらを組み上げられて 作られているように感じました。 なので、タイマーが必要なときは、それをTimerで上書きするだけで .start() .stop() が使えるようになります。 例えば、loop()の中に、透明度を計算して、設定までしてしまうのではなく 設定は、seyOpacity()のように、設定だけ。 うまく自分も細分化して、それらを構築できるわけではありませんが そのように、(なんとなくだけですが)学習したつもり。 それから、書き出しは大文字から始めるそうですよ! fade× Fade○ それと、 Fade = function ( ) {  init: function( ) { ;},  add: function( ) { ; },  set: function( ) { ; } }; のようにすると、大風呂敷をひいて、その中にプログラムを詰め込んで 呼ばれるたびに、それら全部を持って歩くような感じがしています。 Fade = function ( ) {  this.init.apply( this, arguments ); }; Fade.prototype.init = function () {  ; }; Fade.prototype.add = function () {  ; }; 上のようにすると、必要な所だけ、もろものものがコピーされ 小さい風呂敷だけが、動いているような感じがします 実際これが早いかどうかは定かではありませんが^^; 私はプロのプログラマではありませんが、見易さという点で 普通の改行と、1行空けた改行、2行空けた改行を、最近使い分けるようになりました ショートコーディングが好きなくせに・・・^^; それと、.createも、いろいろな書物やらコードをみると new は、隠ぺいした方が良いと 書いたものがありました。なのでこんな形。 (学習の)師は、Fade.bufferを使わずに、Fade[ id ] とかにして hasOwnProperty でチェックしていたのですが 今は、ダブっても言いように、こちらにしています。 これが良いのかはわかりません。 いつもこんなんだから無駄に回答が多いのだろう。

yyr446
質問者

お礼

アドバイスありがとうございました。

その他の回答 (5)

回答No.5

//その2 Fader.prototype.setOpacity = (function ( ) {  return function ( alpha ) {   var flag = false;   if( 0 > alpha ) {    flag = true;    alpha = 0;   } else if( 100 < alpha ) {    flag = true;    alpha = 100;   }   Decorator.call( this.target.style, this.opacity = alpha );   return flag;  }; })(); Fader.prototype.loop = (function ( ) {  return function ( ) {   var alpha = this.opacity + this.direction * this.step;   this.setOpacity( alpha ) && this.stop( );  }; })(); //__ Fader.buffer = { }; Fader.create = function ( id, interval, opacity ) {  var e, o;  if( o = Fader.buffer[ id ] ) {   o.interval = interval;   o.setOpacity( opacity );  } else if( e = document.getElementById( id ) ) {   opacity = 'number' === typeof opacity ? opacity: 100;   o = new Fader( e, interval || 10, opacity);   Fader.buffer[ id ] = o;  }  return o; }; //__ var abc = Fader.create( 'hoge', 20,0 ); document.onclick = function (e) { abc.fadeIn(); } </script> </body> </html>

yyr446
質問者

お礼

サンプルのご提供どうもありがとうございます。 いろいろな方からサンプルをいただいたので、 じっくり吟味して、クラスオブジェクト見たいなのを 使いこなせるように、研究してみます。 ※最近忙しくて、勉強(趣味)の時間がなかなか取れないのですが....

回答No.4

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <title></title> <body> <div id="hoge"> こんばんは。お勉強中の、「その2」の者です。 回答というよりも、自分のお勉強のために一応動作するものを創ってみました。 (実は、よくわかっていません) </div> <script type="text/javascript"> //@cc_on function Decorator ( alpha ) {  //@ this.filter = 'Alpha(opacity=' + alpha + ')';  this.opacity = alpha / 100 + ''; } function Starter (callbackfn) {  this.timerID = (function (o) {   return setInterval(function () { return callbackfn.call(o); }, o.interval);  })(this); } function Stopper () {  clearInterval( this.timerID );  this.timerID = null; } //__ function Timer ( interval ) {  this.timerID = null;  this.interval = interval || 10; } Timer.prototype.start = function ( listener ) {  return Starter.call( this, listener ); }; Timer.prototype.stop = function ( ) {  return Stopper.call( this ); }; //__ var Fader = function ( ) {  this.initializer.apply( this, arguments ); }; Fader.prototype = new Timer; Fader.prototype.constructor = Fader; Fader.prototype.initializer = (function ( ) {  return function ( target, interval, opacity ) {   this.target = target;   this.interval = interval;   this.direction = 0;   this.step = 1;   this.setOpacity( opacity );  }; })(); Fader.prototype.fadeIn = (function ( ) {  return function ( ) {   this.stop();   this.direction = 1;   this.start( this.loop );  }; })(); Fader.prototype.fadeOut = (function ( ) {  return function ( ) {   this.stop( );   this.direction = -1;   this.start( this.loop );  }; })();

  • my--
  • ベストアンサー率89% (91/102)
回答No.3

>No.2 補足 補足と言うか、いい加減なNo.2は無視の方向で。 突っ込まれる前に、例示として絶えられそうなものにしてみました。 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=shift_jis"> <meta http-equiv="Content-Script-Type" content="text/javascript"> <meta http-equiv="Content-Style-Type" content="text/css"> <title>FadeIn/FadeOut</title> <script type="text/javascript"> function FadeInOut(t) { this.target = document.getElementById(t) || t; } FadeInOut.prototype = { fadein: function(interval) { this.counter = 0; this.timer(interval, 1); }, fadeout: function(interval) { this.counter = 100; this.timer(interval, -1); }, timer: function(int, n) { this.stop(); var that = this; this.timerId = setInterval(function() { that.loop(n); }, int); }, stop: function() { this.timerId && (clearInterval(this.timerId), this.timerId = null); }, loop: function(n) { this.target.style.width = this.counter + "px"; this.target.style.height = this.counter + "px"; this.target.style.opacity = this.counter / 100; this.target.style.filter = "alpha(opacity=" + this.counter + ")"; this.counter += n; if (this.counter < 0 || this.counter > 100) this.stop(); } }; function createFadeInOut(target) { return new FadeInOut(target); } </script> </head> <body> <div> <img id="target" src="*.gif" alt="*" style="width:0px;height:0px;"> </div> <script type="text/javascript"> var FadeInOutObj = createFadeInOut('target'); </script> <div> <button onclick="FadeInOutObj.fadein(1);">フェードイン</button> <button onclick="FadeInOutObj.fadeout(1);">フェードアウト</button> </div> </body> </html> thisはFadeInOutObj(インスタンスオブジェクト)への参照となるわけですが FadeInOutObj直属のプロパティとなるのは値が代入されているtarget、counter、timerIdの3つ。 fadein、fadeout、timer、stop、loop、各関数はコンストラクタFadeInOut.prototypeの メンバとして定義してます。プロパティ(メンバ変数)はインスタンスオブジェクトに。 メソッド(メンバ関数)はコンストラクタ.prototypeに、が基本になるでしょうか。 インスタンスオブジェクトが自身のメンバかようにコンストラクタ.prototypeプロパティへ アクセスする暗黙的な参照をプロトタイプチェーンと呼びます。 誤った解釈があればフォローお願いします。

yyr446
質問者

お礼

解説までしてくれて、どうもありがとうございます。 ご回答をもとにもっと勉強してみます。

  • my--
  • ベストアンサー率89% (91/102)
回答No.2

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "​http://www.w3.org/TR/html4/strict.dtd">​ <html xmlns="​http://www.w3.org/1999/xhtml"​ lang="ja-JP"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="Content-Script-Type" content="text/javascript"> <title>FadeIn/FadeOut</title> <style type="text/css"></style> <script type="text/javascript" charset="utf-8"> <!-- function O(target) { function fadeInOut() { this.target = target; } fadeInOut.prototype = { fadein: function(interval) { this.counter = 0; this.interval = interval; this.timerId = setInterval((function(that) { return function() { that.loop(); }; })(this), this.interval); this.stop = function() { this.timerId && clearInterval(this.timerId); this.timerId = null; }; this.loop = function() { this.target.style.width = this.counter + "px"; this.target.style.height = this.counter + "px"; this.target.style.opacity = this.counter / 100; this.target.style.filter = "alpha(opacity=" + this.counter + ")"; if (++this.counter > 100) this.stop(); }; }, fadeout: function(interval) { this.counter = 100; this.interval = interval; this.timerId = setInterval((function(that) { return function() { that.loop(); }; })(this), this.interval); this.stop = function() { this.timerId && clearInterval(this.timerId); this.timerId = null; }; this.loop = function() { this.target.style.width = this.counter + "px"; this.target.style.height = this.counter + "px"; this.target.style.opacity = this.counter / 100; this.target.style.filter = "alpha(opacity=" + this.counter + ")"; if (--this.counter < 0) this.stop(); } } }; return new fadeInOut; } // --> </script> </head> <body> <div> <image id="target" src="image/yahagi.png" style="width:0px;height:0px;"> </div> <script type="text/javascript"> var instance = O(document.getElementById('target')); </script> <button onclick="O(document.getElementById('target')).fadein(1);">フェードイン</button> <button onclick="O(document.getElementById('target')).fadeout(1);">フェードアウト</button> <button onclick="instance.fadein(1);">フェードイン(インスタンス)</button> <button onclick="instance.fadeout(50);">フェードアウト(インスタンス)</button> </body> </html> 表にあるものを単純に中へ入れただけです。インターバル(引数)は メソッドで受け取る方が使い勝手がよさそうですね。 これだけ書けるんだから、プロトタイプチェーンについて調べれば 理解するのに時間は掛からないと思います。

  • fujillin
  • ベストアンサー率61% (1594/2576)
回答No.1

こんばんは。お勉強中の者です。 回答というよりも、自分のお勉強のために一応動作するものを創ってみました。(実は、よくわかっていません) > var myobj = new fadeinout(ターゲット,インターバルミリ秒); > とインスタンスして > myobj.fadein; > myobj.fadeout; を指定の仕様と考えて、 var myobj = new fade(ターゲットのid, インターバルミリ秒); で動作します。  myobj.fadein()、myobj.fadeout() (サイズは変わりません。透明度のみ変化) 最後のopaqueの呼び出しを、クロージャで書くとどうやらメモリーリークになるらしい(?)ので、分けて書いてますが、これで対策になっているのかどうかもあやふやです。(特に、DOMをそのまま記憶したりしているのでよけいに) 参考にはならないと思いますが、悪い方の見本にはなるかと… 先日、babu_babooさんと似たようなものを作ったここ(↓)でも同じような指摘が… http://oshiete1.goo.ne.jp/qa5588925.html ------------------------------------------------ <html> <head><title>test</title> <script type="text/javascript"> var fade = function(id, interval) { this.params = { opacity:100, step:3, op2:0, iId:null}; this.params.id = id; this.params.interval = interval; this.params.element = document.getElementById(id); } fade.prototype.fadein = function() { this.inout(100); } fade.prototype.fadeout = function() { this.inout(0); } fade.prototype.inout = function(o) { var p = this.params; p.op2 = o; if (p.iId) clearInterval(p.iId); p.iId = setInterval(opaque(this), p.interval); } function opaque(obj) { return function() { var p = obj.params, tmp = p.opacity; if (p.op2 > tmp) { tmp += p.step; if (tmp > p.op2) tmp = p.op2; } else { tmp -= p.step; if (tmp < p.op2) tmp = p.op2; } p.element.style.filter = 'alpha(opacity=' + tmp + ')'; p.element.style.opacity = tmp/100; p.opacity = tmp; if (tmp == p.op2) { clearInterval(p.iId); p.iId = null; } } } </script> </head> <body> <div> <image id="img1" src="A.jpg" alt=""><br> <button onclick="Img1.fadein();">fadein</button> <button onclick="Img1.fadeout();">fadeout</button> </div> <hr> <div> <image id="img2" src="B.jpg" alt=""><br> <button onclick="Img2.fadein();">fadein</button> <button onclick="Img2.fadeout();">fadeout</button> </div> <script type="text/javascript"> //オブジェクト定義 var Img1 = new fade('img1', 80); var Img2 = new fade('img2', 30); </script> </body> </html>

yyr446
質問者

お礼

どうもありがとうございます。 すっきりして分かりやすいです。 .prototype で機能やプロパティを追加するコーディング の方が見やすいし、使いまわししやすそうですね。ちがうかな?

関連するQ&A

  • 画像がフェードインしてからフェードアウトする

    <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Document</title> <script src="jquery.min.js"></script> <script src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js"></script> <script src="https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.min.js"></script> <script> $(function(){ var $grid = $('.grid').masonry({ // options itemSelector: 'none', columnWidth: '.grid__item', gutter: 20, stagger: 30, percentPosition: true, visibleStyle: { transform: 'translateY(0)', opacity: 1 }, hiddenStyle: { transform: 'translateY(100px)', opacity: 0 }, }); var msnry = $grid.data('masonry'); $grid.imagesLoaded(function() { $grid.masonry( 'option', { itemSelector: '.grid__item' }); var $items = $grid.find('.grid__item'); $grid.masonry( 'appended', $items ); }); var nextSlugs = [ 'page2.html', 'page3.html' ]; function getPath() { var slug = nextSlugs[ this.loadCount ]; if( slug ) { return 'https://www.miso.blog/demo/masonry_infinitescroll/'; } } }); </script> </head> <body> <h1>Infinite Scroll - Masonry image grid</h1> <ul class="grid"> <li class="grid__item fadein"> <img src="sdfsafasfas.png"></li> <li class="grid__item fadein"> <img src="sdfsafasfas.png"></li> <li class="grid__item fadein"> <img src="sdfsafasfas.png"></li> <li class="grid__item fadein"> <img src="sdfsafasfas.png"></li> <li class="grid__item fadein"> <img src="sdfsafasfas.png"></li> <li class="grid__item fadein"> <img src="sdfsafasfas.png"></li> <li class="grid__item fadein"> <img src="sdfsafasfas.png"></li> <li class="grid__item fadein"> <img src="sdfsafasfas.png"></li> <li class="grid__item fadein"> <img src="sdfsafasfas.png"></li> </ul> </div> <script> $(function(){ $(window).scroll(function (){ $('.fadein').each(function(){ var position = $(this).offset().top; var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); if (scroll > position - windowHeight + 200){ $(this).addClass('active'); } }); }); }); </script> </body> </html> ------------------------------------------------------------------------------- @charset "utf-8"; body { font-family: sans-serif; line-height: 1.4; font-size: 18px; padding: 20px; max-width: 640px; margin: 0 auto; } .grid { max-width: 1200px; } /* reveal grid after images loaded */ .grid.are-images-unloaded { opacity: 0; } .grid__item, .grid__col-sizer { width: 27%; } .grid__gutter-sizer { width: 2%; } /* hide by default */ .grid__item { margin-bottom: 20px; float: center; } .grid__item--height1 { height: 140px; background: #EA0; } .grid__item--height2 { height: 220px; background: #C25; } .grid__item--height3 { height: 300px; background: #19F; } .grid-item--width2 { width: 400px; } .grid__item img { display: block; max-width: 100%; } .fadein { opacity : 0; transform : translate(0, 100px); transition : all 1s; } .fadein.active{ opacity : 1; transform : translate(0, 0); } 何故か画像がフェードアウトして表示されません。 やりたい事は、ある一定の位置にスクロールして調整して 画像を読み込んでフェードインさせて表示させたいのですが ご教示お願いします。

    • ベストアンサー
    • HTML
  • サムネイルで画像を切り替えるjQuery

    下記サイトを参考にサムネイルで画像を切り替えるjQueryを作成しました。 http://tam-tam.co.jp/tipsnote/javascript/post3351.html 自動で切り替えしないようにスクリプトを一部修正して下記を設置しています。 chromeなどでは問題なくスムーズに切り替わるのですが、 firefoxでは、メイン画像とサムネイルが切り替わる際に (フェードイン・フェードアウトの時) 背景が黒くなってしまいます。 また少し動作が不安定に感じます。 背景は白のままで、出来れば動作も改善させたいのですが、 原因が分からず困っています。 どなたか参考サイトのサンプルで原因が分かる方がおられましたら ご教授いただけないでしょうか。 どうぞ宜しくお願い致します。 $(function (){ //設定 var active="active",interval=6000; var index=0, timerId=null; var tabs=$("#thumbBtn > li"), content=$("#view > p"), cap=$("#caption > li"); //クラスの付与 tabs.each(function(){$(this).removeClass(active);}); content.hide(); cap.hide(); tabs.eq(0).addClass(active); content.eq(0).fadeIn("fast"); cap.eq(0).fadeIn("fast"); //クリックされたらactiveというクラスを付与、 //切り替え、タイマーをリセット tabs.click(function(){ if($(this).hasClass("active")) return; if(timerId) clearInterval(timerId),timerId=null; change(tabs.index(this)); setTimer(); return false; }); //タイマー // setTimer(); // function setTimer(){ // timerId=setTimeout(timeProcess,interval); // return false; // } function timeProcess(){ change((index+1)%tabs.length); timerId=setTimeout(arguments.callee,interval); } //切り替え function change(t_index){ tabs.eq(index).removeClass(active); tabs.eq(t_index).addClass(active); //fadeout setTimeout(function(){ content.eq(index).stop(true, true).fadeOut(3000), cap.eq(index).stop(true, true).hide() ;}, 300); //fadein setTimeout(function(){ index=t_index; content.eq(index).fadeIn(3000), cap.eq(index).fadeIn(3000) ;}, 400) } });

  • jQueryでの画像のフェードインのループ

    jQuery初心者です。 jQueryで3枚の背景画像がフェードインで切り替わり、ループするようにしたいのですが、 下記のように書いてみたのですが、1週ループまでは上手くいくのですが、2週目に2枚目の画像で止まってしまいます。 下記だと何故2週目の2枚目で止まるのか?の原因と、スマートな書き方をご教授頂けませんか? <head> <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script> </head> <script> $(function() { $("div.fadein_1").fadeIn(1000); setInterval(function(){ $("div.fadein_2").delay(4000).fadeIn(1000, function(){ $("div.fadein_3").delay(4000).fadeIn(1000, function(){ $("div.fadein_2").attr('style', 'display:none;'); $("div.fadein_3").fadeOut(1000, function(){ clearQueue(); }); }); }); }, 0); }); </script> <div class="fade"> <div class="fadein_1" style="display:none;"></div> </div> <div class="fade"> <div class="fadein_2" style="display:none;"></div> </div> <div class="fade"> <div class="fadein_3" style="display:none;"></div> </div>

  • 3枚の画像をフェードイン

    3枚の画像を順番にフェードインさせたいのですが、IEで確認すると先にパっと画像が表示された後にすぐにその画像が消えてフェードインが次々始まります・・・。何かソース等ミスがあるのかIE対策をしないといけないのかわかりません・・。ページを表示させたあと更新を押すと正常に動くのですがブラウザを閉じて再度表示させるとまたパっと画像が現れた後にフェードインが始まる感じです。 ソースは下記になります。 最初のパッと画像が現れる原因と対策を教えてください・・・! <script type="text/javascript"> $(function(){  $('#fade li').hide(); }); $(window).bind("load", function(){  var interval = 400; //表示間隔  for(var i=0; i<$('#fade li').length; i++)   setTimeout(doFade(i), interval * i);  function doFade(i){   return function(){ $('#fade li').eq(i).fadeIn(2000); };  } }); </script> 【HTML】 <ul id="fade"> <li><img src="image/mainpx_01.jpg" alt="" width="365" height="484" style="display: inline; " /></li><li><img src="image/mainpx_02.jpg" alt="" width="365" height="484" style="display: inline; " /></li><li><img src="image/mainpx_03.gif" alt="" width="270" height="484" style="display: inline; " /></li></ul>

  • javascriptでのフェードイン

    javascriptで画像表示をフェードインにしたいと思っております。 ネット上の情報から以下のソースを使用しております。 1html上に一つの画像を配置すると問題無く機能するのですが、 複数の画像を表示しようとすると一つ目の画像しか表示されません。 どこを変更すれば良いのか分からず困っております・・・ 修正方法、もしくはもっと簡単な方法がございましたら教えていただけないでしょうか。 ※以下のサンプルでは画像は二つですが、実際の使用時には制約上は無制限で画像を配置する予定です。 (Photologのサムネイル表示での使用を想定しております。) ///javascript file/// document.write("<style type='text/css'>#thephoto {visibility:hidden;}</style>"); window.onload = function() {initImage()} function initImage() { imageId = 'thephoto'; image = document.getElementById(imageId); setOpacity(image, 0); image.style.visibility = "visible"; fadeIn(imageId,0); } function fadeIn(objId,opacity) { if (document.getElementById) { obj = document.getElementById(objId); if (opacity <= 100) { setOpacity(obj, opacity); opacity += 25; window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 100); } } } function setOpacity(obj, opacity) { opacity = (opacity == 100)?99.999:opacity; // IE/Win obj.style.filter = "alpha(opacity:"+opacity+")"; // Safari<1.2, Konqueror obj.style.KHTMLOpacity = opacity/100; // Older Mozilla and Firefox obj.style.MozOpacity = opacity/100; // Safari 1.2, newer Firefox and Mozilla, CSS3 obj.style.opacity = opacity/100; } window.onload = function() {initImage()} //////////////////////// ///html file/// <html> <head> <title></title> <script type="text/javascript" src="fade.js"></script> </head> <body> <img src="img_01.jpg" id="thephoto" /></div> <img src="img_02.jpg" id="thephoto" /></div> </body> </html> //////////////////////// どなかたご教授いただけますでしょうか。 何卒、宜しくお願い申し上げます。

  • javascriptでのフェードイン

    javascriptを使用してhtml上の画像をフェードインにて表示したいと思っております。 ネット上の情報とこちらのサイトでのアドバイスを元に以下のソースを使用しておりますが WindowsのIE(6&7)で確認すると「エラー:オブジェクトがありません」と表示されてしまいます。 こちらで確認したところjavascript最後の行の「window.onload~」がエラーの原因となっているようなのですが、 修正する記述方法が分からず困っております。 解決策をご存じの方がおられましたらお手数ですが、 ご教授いただけないでしょうか。 何卒、宜しくお願い申し上げます。 ///javascript file(fade.js)/// document.write("<style type='text/css'>#thephoto1 {visibility:hidden;}</style>"); document.write("<style type='text/css'>#thephoto2 {visibility:hidden;}</style>"); document.write("<style type='text/css'>#thephoto3 {visibility:hidden;}</style>"); function initImage() { for(i=1;i<4;i++){ imageId = 'thephoto' + i; image = document.getElementById(imageId); setOpacity(image, 0); image.style.visibility = "visible"; fadeIn(imageId,0); } } function fadeIn(objId,opacity) { if (document.getElementById) { obj = document.getElementById(objId); if (opacity <= 100) { setOpacity(obj, opacity); opacity += 25; window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 100); } } } function setOpacity(obj, opacity) { opacity = (opacity == 100)?99.999:opacity; // IE/Win obj.style.filter = "alpha(opacity:"+opacity+")"; // Safari<1.2, Konqueror obj.style.KHTMLOpacity = opacity/100; // Older Mozilla and Firefox obj.style.MozOpacity = opacity/100; // Safari 1.2, newer Firefox and Mozilla, CSS3 obj.style.opacity = opacity/100; } window.onload = function() { initImage() } //////////////////////// ///html file/// <html> <head> <script type="text/javascript" src="fade.js"></script> </head> <body> <img src="img_01.jpg" id="thephoto1" /> <img src="img_02.jpg" id="thephoto2" /> <img src="img_03.jpg" id="thephoto3" /> </body> </html> ////////////////////////

  • Firefoxとクロームでフェードインにならない

    横並びの画像を3枚時間差でフェードイン(左から順に表示)させたいのですが、 IEでは問題無く動くのですがFirefoxとGoogle Chromeではフェードインにも透過にもならず画像がそのままパっとでてしまいます・・。 FirefoxとGoogle Chrome対策ソース、他に良い方法などございましたら ご教授いただけますでしょうか。宜しくお願いいたします! <script type="text/JavaScript"> // 画像のフェードイン・フェードアウト var myspd = 5; // 変化する速さ(ミリ秒単位) var myx = 10; // 何%ずつ変化させるか var mypic = new Array("px1","px2","px3"); // 画像のname(順番に並べる) var mycnt = 0; var myp = 0; function mygo() { document.images[mypic[myp]].filters['alpha'].opacity = mycnt; mycnt += myx; if(mycnt >= 100) { mycnt = 0; myp++; } if(mypic.length <= myp) return; setTimeout("mygo()",myspd); } </script> 【HTML】 <ul> <li><img src="image/mainpx_01.jpg" name="px1" width="365" height="484" style="display: inline; filter:alpha(opacity=2);" /></li> <li><img src="image/mainpx_02.jpg" name="px2" width="365" height="484" style="display: inline; filter:alpha(opacity=0);" /></li> <li><img src="image/mainpx_03.gif" name="px3" width="270" height="484" style="display: inline; filter:alpha(opacity=0);" /></li> </ul>

  • ランダムなフェードインを作りたいです。

    jQueryのfadein()/feadeOut()メソッドでイメージのスライドショーを実装したサンプル http://jsajax.com/articles/jQuerySimplestSlidesh … の画像を順番通りでなくランダム表示に修正したいです。 自分なりに考えて作ってみたのですが、正しく機能しませんでした。 どこをどのように修正すればランダムになるのでしょうか? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitio … <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Simplest jQuery Slideshow</title> <style type="text/css"> body {font-family:Arial, Helvetica, sans-serif; font-size:12px;} .fadein { position:relative; height:332px; width:500px; } .fadein img { position:absolute; left:0; top:0; } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4. … <script type="text/javascript"> var imglist = new Array( "http://farm3.static.flickr.com/2610/4148988872_9 … "http://farm3.static.flickr.com/2597/4121218611_0 … "http://farm3.static.flickr.com/2531/4121218751_a … var select = Math.floor((Math.random() * 100)) % imglist.length; var t0 = "<img src='"+imglist[select]+"' border='0' >"; $(function(){ $('.fadein img:gt(0)').hide(); setInterval(function() { $('.fadein :first-child').fadeOut() .next('t0').fadeIn() .end().appendTo('.fadein'); }, 3000); }); </script> </head> <body> <div class="fadein"> <img src="http://farm3.static.flickr.com/2610/4148988872_9 … alt="" /> <img src="http://farm3.static.flickr.com/2597/4121218611_0 … alt="" /> <img src="http://farm3.static.flickr.com/2531/4121218751_a … alt="" /> </div> </body> </html>

    • ベストアンサー
    • AJAX
  • 続き] divの背景画像を、徐々に表示させるには?

    トップページの2つのdivボックスの背景画像を、徐々に表示されるようにするjavascriptを作って頂いたのですが、リピートをやめる方法を御教えいただくのを忘れてしまいました! (http://oshiete1.goo.ne.jp/qa3921804.html) リピートをとめるには、下記ソースをどのようにすればよろしいでしょうか? ------------------------------------------------------------ fade.js ------------------------------------------------------------ var after = 10; // 秒数を指定 var tid1; var tid2; window.onload = function () { fdi2(); tid2=window.setInterval("fdi2()", after*1000); }; function fdi2() { var img1 = document.getElementById("limg"); img1.style.visibility = "visible"; fadeIn("limg", 0); var img2 = document.getElementById("rimg"); img2.style.visibility = "visible"; fadeIn("rimg", 0); } function fadeIn(imgId, opacity) { if (opacity <= 100) { setOpacity(document.getElementById(imgId), opacity); opacity += 10; tid1=window.setTimeout("fadeIn('" + imgId + "'," + opacity + ")", 80); } else { window.clearTimeout(tid1); } } function setOpacity(img, opacity) { img.style.filter = "alpha(opacity:" + opacity + ")"; img.style.KHTMLOpacity = opacity / 100; img.style.MozOpacity = opacity / 100; img.style.opacity = opacity / 100; }

  • JFrameをフェードイン・フェードアウトさせたい

    JFrameを弄って、フェードしている間にJPanelを入れ替えたいと考えています。 newした時だけなぜかフェードイン後になります。 字数制限上省略しているので必要があれば補足などに追記します。 ****** public class MyFrame extends JFrame { public static final int NON_FADE = 0; public static final int IN_FADE = 1; public static final int FADE_OUTING = 2; public static final int FADE_INING = 3; private FadePane pane; private JPanel nowPanel; private Color fadeColor = Color.BLACK; private int fadeTime = 500; private int fadeStatus = NON_FADE; private boolean fadable = true; public MyFrame() { pane = new FadePane(); setGlassPane(pane); fadeOut(0, fadeColor); } public void fadeOut(int time, Color color) { setFadeColor(color); if (fadeStatus != NON_FADE) { return; } fadeStatus = FADE_OUTING; pane.fadeOut(time, color); fadeStatus = IN_FADE; } public void fadeIn(int time) { if (fadeStatus != IN_FADE) { return; } fadeStatus = FADE_INING; pane.fadeIn(time, getFadeColor()); fadeStatus = NON_FADE; repaint(); } public void setFadeColor(Color color) { if (color == null) { return; } if (fadeColor.equals(color)) { return; } fadeColor = color; this.getContentPane().setBackground(fadeColor); this.getContentPane().repaint(); } public void setPanel(JPanel panel) { if (fadable && !(nowPanel == null)) { fadeOut(fadeTime, fadeColor); } if(nowPanel!=null)this.getContentPane().remove(nowPanel); nowPanel = panel; if(nowPanel!=null)this.getContentPane().add(nowPanel); nowPanel.repaint(); if (fadable && !(nowPanel == null)) { fadeIn(fadeTime); } } private class FadePane extends JComponent { private JComponent com = this; private Color color = Color.BLACK; private final int renewalTime = 10; public void fadeOut(int time, Color color) { this.color = color; int red = color.getRed(); int green = color.getGreen(); int blue = color.getBlue(); int alpha = color.getAlpha(); FadeListener listener = new FadeListener(true, red, green, blue, alpha, time, renewalTime, this); Timer timer = new Timer(renewalTime, listener); listener.setTimer(timer); timer.start(); synchronized (this) { try { wait(); } catch (InterruptedException ex) { ex.printStackTrace(); } } } public void fadeIn(int time, Color color) { this.color = color; int red = color.getRed(); int green = color.getGreen(); int blue = color.getBlue(); int alpha = color.getAlpha(); FadeListener listener = new FadeListener(false, red, green, blue, alpha, time, renewalTime, this); Timer timer = new Timer(renewalTime, listener); listener.setTimer(timer); timer.start(); synchronized (this) { try { wait(); } catch (InterruptedException ex) { ex.printStackTrace(); } } } public synchronized void wakeup() { notifyAll(); } @Override protected void paintComponent(final Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setColor(color); g2.fillRect(0, 0, this.getWidth(), this.getHeight()); } private class FadeListener implements ActionListener { //true:フェードアウト //false:フェードイン final boolean mode; final int red; final int green; final int blue; final int alpha; Timer timer; final int allTime; int time = 0; final int dTime; FadePane pane; public FadeListener(boolean mode, int red, int green, int blue, int alpha, int time, int dTime, FadePane pane) { this.mode = mode; this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; this.allTime = (time / dTime) + 1; this.dTime = dTime; this.pane = pane; } public void setTimer(Timer timer) { this.timer = timer; } @Override public void actionPerformed(ActionEvent e) { if (time == 0) { com.setVisible(!mode); } time++; if (time > allTime) { com.setVisible(mode); timer.stop(); pane.wakeup(); return; } com.setVisible(true); int nowAlpha = mode ? alpha * time / allTime : alpha - (alpha * time / allTime); color = new Color(red, green, blue, nowAlpha); com.repaint(); } } } }

    • ベストアンサー
    • Java

専門家に質問してみよう