問題があります。
(ボタンをクリックした後) 正方形を即座にフェードアウトさせ、その後、時間をかけてゆっくりとフェードインさせたいと考えています。
これは私のフィドルの例です:
クラスを変更しましたが、それは適切なアプローチではありません。
my_square.className = 'dim_fast';
my_square.className = 'square';
助けてくれてありがとう!
問題があります。
(ボタンをクリックした後) 正方形を即座にフェードアウトさせ、その後、時間をかけてゆっくりとフェードインさせたいと考えています。
これは私のフィドルの例です:
クラスを変更しましたが、それは適切なアプローチではありません。
my_square.className = 'dim_fast';
my_square.className = 'square';
助けてくれてありがとう!
さて、あなたの関数では、クラスをに変更しdim_fast
、すぐにに戻りますsquare
。これには遷移がありません:)
したがって、次を削除します。
my_square.className = 'square';
または、少なくとも 2 番目のクラスを追加します。
my_square.className = 'square dim_fast';
四角形をフェードアウトし、一定時間後にフェードインするには、 を使用できますsetTimeout
。
例
まず、ボタンが正方形の前に配置されていることを確認する必要があります。
<button id="bt1"> </button>
<div id="my_square" class="square"> </div>
これは、CSS に「前の兄弟」セレクターがないためです。
:active
ここで、正方形を直接非表示にするために、ボタンで疑似要素を使用する必要があります。
#bt1:active + .square
{
-webkit-transition:opacity 0s;
-moz-transition:opacity 0s;
-o-transition:opacity 0s;
transition:opacity 0s;
opacity:0;
}
ボタンをクリックすると、正方形が即座に非表示になります。
次に、正方形にトランジションを追加します。
.square
{
-webkit-transition:opacity 2s;
-moz-transition:opacity 2s;
-o-transition:opacity 2s;
transition:opacity 2s;
opacity:1;
}
スクエアは 2 秒でフェードインします。
これにはトランジションの代わりにアニメーションを使用します
変更された CSS (あなたの jsfiddle から)
.square
{
width:100px;
height:100px;
background-color:blue;
opacity:1;
}
.fade{
animation: dim_fast_shine_slow 1s;
}
@keyframes dim_fast_shine_slow{
99%{opacity:0;}
100%{opacity:1}
}
変更されたスクリプト
var my_square = document.getElementById('my_square');
function dim_fast_shine_slow()
{
// remove class
my_square.className = my_square.className.replace(' fade','');
setTimeout(function(){
// add class after 50 millisecons to allow the DOM to register the removal of the class
my_square.className += ' fade';
},50);
}
document.getElementById('bt1').onclick = dim_fast_shine_slow;
次のように簡単です。
function dim_fast_shine_slow() {
my_square.classList.toggle("dim_fast");
}
あなたのバージョンでは:
function dim_fast_shine_slow() {
my_square.className = 'dim_fast'; //changes class to dim_fast
my_square.className = 'square'; // changes it back to square
}
クリックするたびに、要素のクラス名は「正方形」になります。
jQueryなしでそれを行う方法があるはずです(私は気づいていません)..しかし、jQueryを使用することにした場合:
$(my_square).hide("fast").show("slow");