JavaScript-Dot导航

时间:2015-04-01 02:03:13

标签: javascript jquery css html5

如何对Javascript或jQuery进行编码,以便当我点击一个点时,点会获得一个活动类,但之前的点类被删除了?

HTML:

<div class="dotnav">
    <div class="dot active" title="Sign Up"></div>
    <div class="dot" title="hello"></div>
    <div class="dot" title="hello"></div>
    <div class="dot" title="hello"></div>
    <div class="dot" title="hello"></div>
    <div class="dot" title="helloup"></div>
</div>

CSS:

.dotnav {
    left: 40px;
    position: absolute;
    top: 50%;
    z-index: 9999;
    display: block;
    /*-webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    transform: translateY(-50);*/
}

.dot {
    width: 16px;
    height: 16px;
    border-radius: 100%;
    border: 2px solid #CCCCCC;
    display: block;
    margin-top: 10px;
    cursor: pointer;
    vertical-align;
    baseline;
}

.dot:hover {
    border: 2px solid #999999;
    background-color: #C9931E;
}

.active {
    background-color: #C9931E;
}

如何编写Javascript或jQuery代码,以便当我点击一个点时,点会获得一个活动类,但之前的点类被删除了?

4 个答案:

答案 0 :(得分:0)

$('.dot').on('click', function() {
    $('.dot.active').removeClass('active');
    $(this).addClass('active');
});

答案 1 :(得分:0)

你可以这样做:

$('.dot').click(function(){
    this.className = 'active';
});

DEMO

答案 2 :(得分:0)

单击,删除活动类,然后在单击的点上添加active。像这样:

$('.dot').click(function () {
    $('div.active').removeClass('active');
    $(this).toggleClass('active');
});

Fiddle here.

答案 3 :(得分:0)

// Use on(), not click(); It's easier to read when in complex code, and you can namespace your event.
// ALWAYS namespace your events
// It's also a good idea to pass your event to your anonymous function - saves lots of time if your patterns are the same
$('.dot').on('click.dot', function(e){
  // Remove 'active' class from all siblings in a single line
  // We remove from siblings so that other 'dot' structures can be used without being interfered with
  // If you want multiple set to sync their behaviour - write in data-attr and sync up that way (new question if you want to give that a go)
  $(this).siblings('.dot').removeClass('active');
  // Then, apply to the current clicked on element
  $(this).addClass('active');
})

j使用原始HTML和CSS:http://jsfiddle.net/q5p6fj5y/1/