使用JQuery在样式之间切换

下午好,

我正在寻找一种在样式之间切换的方法:

例:

我有两个样式(类),一个使段落变红,另一个使段落变蓝。 我只想使用JQuery来调用样式,而不是自己保存样式。

因此,当我单击按钮时,段落变为红色,当我再次单击时,它变为蓝色。

同样,我宁愿将样式分开并给出类名,并在两者之间切换JQuery。

我已经搜索了网络,但不断提出显示/隐藏示例,其中样式嵌入到JQuery函数中。

任何想法将不胜感激!

奥维马斯

大家好! 这就是我所做的,正如我所提到的,我只是试图在两种风格之间切换。 一种风格做了一些事情,例如:使文本变红或改变图像,而另一种风格使另一种事情发生。

感谢每一位耐心的人。 你们都有所作为。

我在JQuery Cook Book中找到了答案。 第3章事件处理页面69.以下是代码:

$(document).ready(function() { $('.normalStyle').click(function(){ $(this).toggleClass('newStyle'); }); }); 

使用toggleClass

根据类的存在或switch参数的值,从匹配元素集中的每个元素添加或删除一个或多个类。

 $('div.foo').toggleClass(function() { if ($(this).is('.blue')) { return 'red'; } else { return 'blue'; } }); 

此示例将切换

元素的blue类,如果它们的父元素是red类; 否则,它将切换blue类。

甚至更短:

  $('div.blue').toggleClass('red'); 

切换的类会使初始颜色变为原始颜色(刚刚添加了红色类),如下所示:

  $('div.blue').click(function() { $(this).toggleClass('red'); }); 

在这里小提琴

或者使用非常纯粹的类替换(删除蓝色并添加红色和vv):

 $('div').click(function() { $(this).toggleClass('red blue') }); 

在这里小提琴

您可以使用.toggleClass()来打开和关闭类以更改文本颜色。

 $("#someButton").click(function(){ $("#someP").toggleClass("makeRed"); }); 

关于jsfiddle的简单示例

请看这篇文章。 jquery背景从图像到颜色再回来

我希望它会有所帮助:-)

它与我所了解的基本相同。

您可以将样式设置为红色/蓝色,而不是在图像和颜色之间进行切换。

我想你需要这样的东西:

基于jQuery构建的Styleswitch样式表切换器http://www.kelvinluck.com/2009/07/jquery-styleswitch-now-with-toggle/

试试这个:

         
Good afternoon, I am searching for a way to Toggle between styles: Example: I have two styles(classes), one makes the paragraph red and the other makes the paragraph blue. I only want to use JQuery to call the styles, not to hold the styles itself. So when I click a button, the paragraph turns red, when I click again, it turns blue. Again, I would rather have the style separate and given class names and have JQuery switch between the two. I have search the net but keep coming up with show/hide examples where the styles are embedded into the JQuery function. Any ideas will be appreciated!