jQuery style manipulation

     This morning, I learned the methods of JQuery style setting, appending, removing and switching. With JQuery, styling elements becomes easy.

Get and set styles

Both getting the class and setting the class can be done using the attr() method. For example, using the attr() method to get the class of the p element, the JQuery code is as follows:

var p_class = $("p").attr("class");
//Get the class of the p element

Use the attr() method to set the class of the p element. The JQuery code is as follows:

$("p").attr("'class", "high");
//Set the class of the p element to "high"

In most cases, it replaces the original class with the new class, rather than appending the new class to the original.

Append style

  If the original class of the p element is myClass, then after adding a class named high, the class attribute becomes "myClass high", that is, the superposition of the two styles of myClass and high. JQuery provides a special addClass() method to append styles. To make the example easier to understand, first add another set of styles to the style tag:

.high{ color:red; }
.another{ font-style:italic; color:blue; }

Then add a button of "Append class" to the web page. The event code of the button is as follows:

$("#btn_3").click(function(){
  $("#nm_p").addClass("another");
  // append style
});

最后当单击“追加class类”按钮时,p元素样式就会变为斜体,而先前的红色字体也会变为蓝色。此时p元素同时拥有两个class值,即"high"和"another"。在CSS中有以下两条规定。

1. 如果给一个元素添加了多个class值,那么就相当于合并了它们的样式。
2. 如果有不同的class设定了同一样式属性,则后者覆盖前者。

在上例中,相当于给p元素添加了如下样式:

color : red;  /* 字体颜色设置红色*/ 
font-style:italic; 
color:blue;

在以上的样式中,存在两个“color”属性,而后面的“color”属性会覆盖前面的“color”属性,因此最终的“color”属性的值为“blue”,而不是“red”。

移除样式

如果用户单击某个按钮时,要删除class的某个值,那么可以使用与addClass()方法相反的removeClass()方法来完成,它的作用是从匹配的元素中删除全部或者指定的class。例如可以使用如下的JQuery代码来删除p元素中值为“high”的class:

$("p").removeClass("high");
//移除p元素中值为"high"的class

如果要把p元素的两个class都删除,就要使用两次removeClass()方法,代码如下:

$("p").removeClass("high").removeClass("another");

JQuery提供了更简单的方法。可以以空格的方式删除多个class名,代码如下:

$("p").removeClass("high another");

另外,还可以利用removeClass()方法的一个特性来完成同样的效果。当它不带参数时,就会将class的值全部删除,JQuery代码如下:

$("p").removeClass();
//移除p元素的所有class

切换样式

JQuery中有一个方法toggle(),JQuery代码如下:

toggleBtn.toggle(function(){
 元素显示 
}, function(){
元素隐藏
})

toggle()方法此处的作用是交替执行两个函数,如果元素原来是显示的,则隐藏它:如果元素原来是隐藏的,则显示它。此时,toggle()方法主要是控制行为上的重复切换。

另外JQuery还提供了一个toggleClass()方法控制样式上的重复切换。如果类名存在则删除它,如果类名不存在则添加它。例如对p元素进行toggleClass()方法操作。

$("p").toggleClass("another");
//重复切换类名“another”

当不断单击“切换样式”按钮时,p元素的class的值就会在“myClass”和“myClass another”之间重复切换。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326071278&siteId=291194637