我有一個非常簡單的目標,我試圖用jQuery來完成。我有6個「觸發」divs,將「selected」類添加到相應的段落。目前已設置並正在運行,因此當您將鼠標懸停在div
之上時,paragraph
1會得到一個類切換。我想更進一步,如果您實際上點擊了div
1,則「選定」類將保留在段落上,直到您單擊另一個觸發器div或單擊文檔中的其他位置。jQuery - 懸停功能覆蓋點擊功能
這裏有一個Codepen出什麼我現在有:http://codepen.io/trevanhetzel/pen/yKnAf
而這裏的代碼:
<div class="triggers">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
<div class="five"></div>
<div class="six"></div>
</div>
<div class="paragraphs">
<p class="one"></p>
<p class="two"></p>
<p class="three"></p>
<p class="four"></p>
<p class="five"></p>
<p class="six"></p>
</div>
// The goal is to toggle the selected class when you hover over a trigger, BUT if you click on a trigger it will not just toggle the class, but add it so it's "stuck" until you either click out of the .paragraphs containing div or click on another trigger. Right now, I think the hover functions are overriding the click functions....also I need to minimize all these stupid functions to keep it DRY...
// Toggle selected class when hovering the triggers
$('.triggers .one').hover(function() {
$('.paragraphs p.one').toggleClass('selected');
});
$('.triggers .two').hover(function() {
$('.paragraphs p.two').toggleClass('selected');
});
$('.triggers .three').hover(function() {
$('.paragraphs p.three').toggleClass('selected');
});
$('.triggers .four').hover(function() {
$('.paragraphs p.four').toggleClass('selected');
});
$('.triggers .five').hover(function() {
$('.paragraphs p.five').toggleClass('selected');
});
$('.triggers .six').hover(function() {
$('.paragraphs p.six').toggleClass('selected');
});
// Add the selected class when clicking a trigger
$('.triggers .one').click(function() {
$('.paragaphs p').removeClass('selected');
$('.paragraphs p.one').addClass('selected');
});
$('.triggers .two').click(function() {
$('.paragaphs p').removeClass('selected');
$('.paragraphs p.two').addClass('selected');
});
$('.triggers .three').click(function() {
$('.paragaphs p').removeClass('selected');
$('.paragraphs p.three').addClass('selected');
});
$('.triggers .four').click(function() {
$('.paragaphs p').removeClass('selected');
$('.paragraphs p.four').addClass('selected');
});
$('.triggers .five').click(function() {
$('.paragaphs p').removeClass('selected');
$('.paragraphs p.five').addClass('selected');
});
$('.triggers .six').click(function() {
$('.paragaphs p').removeClass('selected');
$('.paragraphs p.six').addClass('selected');
});