2010-12-22 52 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