2010-12-22 51 views
9

我有以下代碼:如何使用jQuery切換CSS?

$('#bc' + $.trim($this) + ' span.dashed-circle').css({ 'border' : '5px solid #000'}); 

即由click.function觸發()。

我希望這是一個切換 - 所以當我點擊元素時,它會將邊框更改爲我上面的內容......但是當它再次單擊時,它會消失或者將邊框設置爲「'。

想法?

編輯:我應該明確......但我不想創建一個CSS類。原因是因爲當我這樣做時,它會擾亂正在設計的元素的格式。我相信這是一個小問題,可以解決這個問題,但我並不想涉足整個代碼庫,以解決一個新類的定位問題。我寧願直接編輯css屬性 - 因爲它不會影響佈局。

編輯2:這是jsfiddle of the code我正在嘗試編輯。如果您注意到,我最後擁有CSS屬性。但是,我如何讓這種切換?

EDIT3:如果有人有興趣......這將在所使用的UI是我的webapp - http://www.compversions.com

+0

看看jQuery的切換:http://api.jquery.com/toggle/ – Cliff 2010-12-22 21:13:48

+0

這是我做的第一件事,但由於我的代碼的方式,它給我的問題。這就是我來這裏的原因。 – marcamillion 2010-12-22 21:24:24

回答

16
$("trigger-element").toggle(function() { 
    $(element-to-change).css({ 'border' : '5px solid #000'}); 
    }, function() { 
    $(element-to-change).css({ 'border' : 'none'}); 
}); 

嘗試這個

$(document).ready(function() { 
     $('#panels tr table tr').toggle(function() { 
      var $this = $(this), 
       tr_class = 'dash-elem-selected'; 
      if (!$this.parent('thead').length) { 
       if ($this.hasClass(tr_class)) { 
        $this.removeClass(tr_class); 
        tr_class = 'removeClass'; 
       } else { 
        $this.addClass(tr_class).siblings().removeClass(tr_class); 
        tr_class = 'addClass'; 
       } 
       $this = $this.parents('td table').siblings('.sit-in-the-corner').text(); 
       $('#bc' + $.trim($this) + ' span')[tr_class]('bc-dotted-to-solid'); 
       $('#bc' + $.trim($this) + ' span.dashed-circle').css({ 'border' : '5px solid #000'}); 
      } 
     }, function() { 
    //This is your new function that will turn off your border and do any other proccessing that you might need. 
$('#bc' + $.trim($this) + ' span.dashed-circle').css({ 'border' : 'none'}); 
}); 
    }); 
+0

我認爲這是最接近我想要做的。 – marcamillion 2010-12-22 21:23:51

+0

但是,我不太清楚如何將其應用於我的代碼:http://jsfiddle.net/BMWZd/4/想法? – marcamillion 2010-12-22 22:02:35

+0

試試我上面的編輯。 – Cole 2010-12-22 22:10:54

4

Use toggle.

$("#IDOfElementYouClickOn").toggle(
     function(){$('#bc' + $.trim($this) + ' span.dashed-circle').css({ 'border' : '5px solid #000'});}, 
     function(){$('#bc' + $.trim($this) + ' span.dashed-circle').css({ 'border' : ''});} 
    ); 
15

我會通過定義withborder類和togglin來做到這一點克那班。

CSS:

.withborder { 
    border: 5px solid #000; 
} 

的jQuery:

$('#bc' + $.trim($this) + ' span.dashed-circle').click(function(){ 
    $(this).toggleClass('withborder'); 
}); 
12

你可以爲這個

.specialborderclass { 
    border: 5px solid #000; 
} 

創建CSS類,然後執行JavaScript中使用切換jQuery toggleClass() method