制作.click覆盖.on('mouseover')

时间:2014-11-19 09:39:53

标签: jquery html

我正在制作一个时间轴,它会在悬停时显示信息,但我也希望它可以点击,点击后,保持可见,直到点击另一个按钮,或再次点击该按钮。我该怎么做?

JSFIDDLE

我的HTML:

<div class="timeline-pills">
        <div class='timeline-element' id='year-1492'>
            <p>1492</p>
        </div>
        <div class='timeline-element' id='year-1607'>
            <p>1607</p>
        </div>
        <div class='timeline-element' id='year-1620'>
            <p>1620</p>
        </div>
</div>
<div class="timeline-info-panels">
            <div class='timeline-info' id='1492'>
            <p>1492</p>
        </div>
        <div class='timeline-info' id='1607'>
            <p>1607</p>
        </div>
        <div class='timeline-info' id='1620'>
            <p>1620</p>
        </div>
</div>

我的jQuery:

$('.timeline-element').on('mouseenter', function(){
$(this).addClass('hover-over-time-pill')
$('.timeline-info-panels').show();

var hoverID = $(this).attr("id");
var newID = hoverID.replace('year-', '');
$('#'+newID).show();
});

$('.timeline-element').on('mouseleave', function(){
$(this).removeClass('hover-over-time-pill')
$('.timeline-info-panels').hide();

var hoverID = $(this).attr("id");
var newID = hoverID.replace('year-', '');
$('#'+newID).hide();    
});

$('.timeline-element').click(function(){
    $(this).addClass('timeline-click');
    $('.timeline-info-panels').show();

    var clickID = $(this).id;
    var newID = clickID.substring(0,5);
    $('#'+newID).show();
});
$('.timeline-element').click(function(){
    $(this).removeClass('timeline-click');
    $('.timeline-info-panels').hide();

    var clickID = $(this).id;
    var newID = clickID.substring(0,5);
    $('#'+nweID).hide();
});

2 个答案:

答案 0 :(得分:0)

您必须使用jQuery的.off()方法将侦听器解除绑定到使用.on()方法添加的mouseenter和mouseleave事件,并在第二次单击按钮时再次添加它们。

答案 1 :(得分:0)

您可以在点击活动中设置有效时间轴。

首先在点击时添加活动类药丸和信息。

$('.timeline-element').click(function () {

    // Removes old active elements for second click
    $('.timeline-element.active,.timeline-info.active').removeClass('active');

    var hoverID = $(this).attr("id");
    var newID = hoverID.replace('year-', '');

    // Set active
    $('#' + newID).addClass('active');
    $(this).addClass('active');
});

然后转到css并为活动类编写新样式。

.timeline-info.active {
    display:block !important;
}
.timeline-element.active{
    background-color: #051A5B;
}

http://jsfiddle.net/s4yvbqzL/3/有一个有效的演示。

编辑关闭激活的元素

$('.timeline-element').click(function () {

        var deActive = $(this).hasClass('active');

        // Removes old active elements for second click
        $('.timeline-element.active,.timeline-info.active').removeClass('active');

        // If clicked element is not active, activate it.
        if(deActive == false) {
            var hoverID = $(this).attr("id");
            var newID = hoverID.replace('year-', '');

            // Set active
            $('#' + newID).addClass('active');
            $(this).addClass('active');
        }
    });

工作演示http://jsfiddle.net/s4yvbqzL/4/