我有一个非常简单的目标,我正在尝试使用 jQuery 来实现。我有 6 个“触发” div,它们将“选定”类添加到相应的段落中。它目前已设置并正在工作,因此当您将鼠标悬停在div
1 上时,paragraph
1 会切换一个类。我想更进一步,如果您实际单击div
1,则“选定”类会保留在段落中,直到您单击另一个触发器 div 或单击文档上的其他位置。
这是一个显示我现在拥有的 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');
});