2016-10-10 1 views
2

したがって、CSSを使用してボタンに3Dエフェクトを追加しようとしています。私はそれに下の境界線を与え、ホバー上/クリックすると、私は境界線のサイズを変更し、相対位置を使用して同じ量を押し下げます。クリックイベントでCSSを使用するボタンエフェクト

これはうまくいきますが、ボタンの上端付近をクリックすると、クリックイベントが発生しません。おそらく、ボタンがポインタの途中で移動したためです。

Clickイベントに干渉することなく、この効果を達成する別の方法(追加のマークアップではなく純粋なCSSを使用)がありますか?

例:

var initialCount = 0; 
 
window.incrementCounter = function() { 
 
    document.getElementById('counter').innerHTML = 'Counter: ' + ++initialCount; 
 
}
#counter { 
 
    margin-bottom: 1em; 
 
} 
 

 
button { 
 
    background: #ccc; 
 
    border: none; 
 
    border-bottom: 3px solid #aaa; 
 
    font-size: 16px; 
 
    padding: 5px 10px; 
 
    position: relative; 
 
} 
 

 
button:hover { 
 
    border-bottom-width: 2px; 
 
    top: 1px; 
 
} 
 

 
button:active { 
 
    border-bottom-width: 0; 
 
    top: 3px; 
 
}
<div id="counter">Counter: 0</div> 
 
<button id="button" onClick="window.incrementCounter()">Increment</button>

答えて

2

問題は、あなたが一度だけ成功しmousedownmouseupイベントをトリガさに結合しているclickイベントが発生しているということです。 mouseupイベントが発生すると、ターゲットはボタンではなくなりました(移動されたため)。

var initialCount = 0; 
 
window.incrementCounter = function() { 
 
    document.getElementById('counter').innerHTML = 'Counter: ' + ++initialCount; 
 
}
#counter { 
 
    margin-bottom: 1em; 
 
} 
 

 
button { 
 
    background: #ccc; 
 
    border: none; 
 
    border-bottom: 3px solid #aaa; 
 
    font-size: 16px; 
 
    padding: 5px 10px; 
 
    position: relative; 
 
} 
 

 
button:hover { 
 
    border-bottom-width: 2px; 
 
    top: 1px; 
 
} 
 

 
button:active { 
 
    border-bottom-width: 0; 
 
    top: 3px; 
 
}
<div id="counter">Counter: 0</div> 
 
<button id="button" onmousedown="window.incrementCounter()">Increment</button>

<button id="button" onmousedown="window.incrementCounter()">Increment</button> 

作業のデモについては、以下のスニペットを参照してください:次のように

あなたのための最も簡単な回避策は、clickではなく、mousedownイベントにごincrementCounter()機能をバインドすることです

ただし、ob厄介なイベントハンドラはかなり悪い習慣です。 DOMの外で(つまり、JS内で直接)リスナーを使用する方がよいでしょう。

+0

マウスダウンイベントは私の問題をきれいに解決します。そして、はい、これはちょうど私のスニペットの簡潔さのためでした - 実際のアプリケーションでは、イベントハンドラはJSを介してバインドされています。 –

+0

全く問題はありませんが、おそらくテストケースだと思っていましたが、とにかく言いたいと思いました!喜んで助けてくれた。 – BenM

0

異なる解決方法は、相対的な配置の代わりにマージンを使用することです。あなたはまた、CSSでw3.css使用することができます

var initialCount = 0; 
 
window.incrementCounter = function() { 
 
    document.getElementById('counter').innerHTML = 'Counter: ' + ++initialCount; 
 
}
#counter { 
 
    margin-bottom: 1em; 
 
} 
 

 
button { 
 
    background: #ccc; 
 
    border: none; 
 
    margin-top: 0; 
 
    border-bottom: 3px solid #aaa; 
 
    font-size: 16px; 
 
    padding: 5px 10px; 
 
} 
 

 
button:hover { 
 
    border-bottom-width: 2px; 
 
    margin-top: 1px; 
 
} 
 

 
button:active { 
 
    border-bottom-width: 0; 
 
    margin-top: 3px; 
 
}
<div id="counter">Counter: 0</div> 
 
<button id="button" onmousedown="window.incrementCounter()">Increment</button>

0

。 w3.cssは非常に簡単なスタイリングフレームワークです。使用

<div class="w3-hover"> for hover effect. 
関連する問題