2015-04-01 95 views
-2

我該如何編寫JavaScript或jQuery代碼,以便當我點擊一個點時點獲得一個活動類,但之前的點類被刪除?JavaScript-Dot導航

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的,這樣,當我點擊一個點,該點得到一個活動類,但之前的點類被刪除?

回答

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

由於它的工作。 – MasterRaining 2015-04-01 02:12:59

0

您可以簡單地這樣來做:

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

DEMO

0

點擊後,刪除然後活動類上的點擊點加active。事情是這樣的:

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

Fiddle here.

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'); 
}) 

jFiddle與你原來的HTML和CSS:http://jsfiddle.net/q5p6fj5y/1/