开发者

Changing css w/ javascript

So I have a link, that when clicked, i want its css values to change. I can do that with this jquery code:

    $(开发者_C百科".linkname").click(function(){
  $(this).css({'border-style' : 'solid', 'border-width' : '1px', 'border-color' : '#ec6163', 'color' : '#ec6163'});
  return false;
});

However, I also want the link's css values to revert to normal when I click the link with the altered css values a second time. I tried an if else sentence, but it always evaluated else and didn't work. How can i do this?


Even better, put all of that CSS into a class and use toggleClass to switch.

/* CSS */
.someclass { border: 1px solid #ec6163; color: #ec6163; }

/* JS */
$(".linkname").click(function(){
    $(this).toggleClass('someclass');
    return false;
});


Have you tried using toggle()?

$('.linkname').toggle( function() {
        $(this).css({'border-style' : 'solid', 'border-width' : '1px', 'border-color' : '#ec6163', 'color' : '#ec6163'});
    }, function() {
        $(this).css({'border-style' : 'dotted', 'border-width' : '0px', 'border-color' : '#999999', 'color' : '#cc6163'});
});


I am not sure why your if/else statement didn't work.
Perhaps try using a variable outside of the method to save which state the link is in.

eg.

var link_state = 1;

$(".linkname").click(function(){
  if (link_state == 1) {
    $(this).css({'border-style' : 'solid', 'border-width' : '1px', 'border-color' : '#ec6163', 'color' : '#ec6163'});
    link_state = 0;
  }
  else {
    $(this).css({'border-style' : 'none', 'border-width' : '0px', 'border-color' : '#ffffff', 'color' : '#ffffff'});
    link_state = 1;
  }
  return false;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜