如果你委託你的所有樣式的CSS類,然後讓所有你需要做的,你可以簡化您的問題是在hover
和click
上更改箱子的等級。
例如,假設標記:
<div class="box">container one</div>
<div class="box">container two</div>
和CSS:
.box {
display: inline-block;
height: 200px;
width: 400px;
background: #cdcdcd;
}
.box.hovered, .box.clicked {
background: #797979;
}
就像你用後,可以實現它的聲音效果:
// Handle the mouseenter/leave events with a unique class
$('.box').on('mouseenter', function() {
$(this).addClass('hovered');
}).on('mouseleave', function() {
$(this).removeClass('hovered');
});
// Handle click event with a different class and toggle method
$('.box').on('click', function() {
$(this).toggleClass('clicked');
});
另外,如果您希望的框根據點擊開關可以使用:
$('.box').on('click', function() {
$(this).removeClass('hovered');
$(this).siblings('.box').addClass('hovered')
});
// Use this block instead of the previous `click` handler above
到到您的樣式表的抽象風格(而不是使用.css
法)的優點是:
A.你的模樣了從標記(關注點分離)分離,並避免使用內聯樣式覆蓋問題。
B.它通過將問題減少到類的添加/刪除來顯着簡化您的DOM交互。
這裏有一個Fiddle
當我在第二個按鈕懸停應該chanage第二圖像的背景顏色。它工作正常,但是當我點擊那個按鈕,它應該留在那個BG,現在的重點是我添加了一個點擊的類,但是當我徘徊它再次使用該鼠標事件。 – designerNProgrammer