search
HomeWeb Front-endJS TutorialLearn jQuery from scratch (4) Attributes and styles of operating elements in jQuery_jquery

1. Summary
This article explains how to use jQuery to obtain and manipulate element attributes and CSS styles. The distinction between DOM attributes and element attributes is worth learning.

2. Preface
Through the previous chapters, we have been able to fully control the jQuery packaging set, whether it is selecting objects through selectors, or deleting or filtering elements from the packaging set. This chapter will explain how to use jQuery to obtain and modify elements. Attributes and styles.

3. Distinguish between DOM attributes and element attributes
An img tag:

Hibiscus

Usually developers are used to calling id, src, alt, etc. the "attributes" of this element. I call it " Element attributes". However, when parsing into a DOM object, the actual browser will eventually parse the tag element into a "DOM object" and store the element's "element attributes" as "DOM attributes". There is a difference between the two.
Although we set the src of the element to be a relative path: images/image.1.jpg
But it will be converted into an absolute path in the "DOM Attributes": http://localhost/images/image.1.jpg.

Even some "element attributes" and "DOM attributes" have different names, such as the element attribute class above, which corresponds to className after being converted into a DOM attribute.

Keep in mind that in javascript we You can directly get or set "DOM attributes":
Copy code The code is as follows:


$(function() {
var img1 = document.getElementById("hibiscus");
alert(img1.alt);
img1.alt = "Change the alt element attribute";
alert(img1.alt);
})


So if you want to set the CSS style class of the element , use the "DOM attribute "className" instead of the "element attribute" class:

img1.className = "classB";

4. Operation of "DOM attribute"
There is no wrapper function for operating "DOM attributes" in jQuery, because it is very simple to use javascript to get and set "DOM attributes". jQuery provides the each() function for traversing the jQuery wrapper set, where this The pointer is a DOM object, so we can apply this with native javascript to manipulate the DOM attributes of the element:
Copy code The code is as follows :

$("img").each(function(index) {
alert("index:" index ", id:" this.id ", alt:" this.alt );
this.alt = "changed";
alert("index:" index ", id:" this.id ", alt:" this.alt);
});

下面是each函数的说明:

each( callback ) Returns: jQuery包装集
对包装集中的每一个元素执行callback方法. 其中callback方法接受一个参数, 表示当前遍历的索引值,从0开始.

五. 操作"元素属性"
我们可以使用javascript中的getAttribute和setAttribute来操作元素的"元素属性".
在jQuery中给你提供了attr()包装集函数, 能够同时操作包装集中所有元素的属性:
名称 说明 举例

attr( name )

取得第一个匹配元素的属性值。通过这个方法可以方便地从第一个匹配元素中获取一个属性的值。如果元素没有相应属性,则返回 undefined 。 返回文档中第一个图像的src属性值:
$("img").attr("src");
attr( properties )

将一个“名/值”形式的对象设置为所有匹配元素的属性。

这是一种在所有匹配元素中批量设置很多属性的最佳方式。 注意,如果你要设置对象的class属性,你必须使用'className' 作为属性名。或者你可以直接使用.addClass( class ) 和 .removeClass( class ).

为所有图像设置src和alt属性:
$("img").attr({ src: "test.jpg", alt: "Test Image" });
attr( key, value ) 为所有匹配的元素设置一个属性值。 为所有图像设置src属性:
$("img").attr("src","test.jpg");
attr( key, fn )

为所有匹配的元素设置一个计算的属性值。

不提供值,而是提供一个函数,由这个函数计算的值作为属性值。

把src属性的值设置为title属性的值:
$("img").attr("title", function() { return this.src });
removeAttr( name ) 从每一个匹配的元素中删除一个属性 将文档中图像的src属性删除:
$("img").removeAttr("src");
当使用id选择器时常常返回只有一个对象的jQuery包装集, 这个时侯常使用attr(name)函数获得它的元素属性:
复制代码 代码如下:

function testAttr1(event) {
alert($("#hibiscus").attr("class"));
}

注意attr(name)函数只返回第一个匹配元素的特定元素属性值. 而attr(key, name)会设置所有包装集中的元素属性:
复制代码 代码如下:

//修改所有img元素的alt属性
$("img").attr("alt", "修改后的alt属性");

而 attr( properties ) 可以一次修改多个元素属性:
复制代码 代码如下:

$("img").attr({title:"修改后的title", alt: "同时修改alt属性"});

另外虽然我们可以使用 removeAttr( name ) 删除元素属性, 但是对应的DOM属性是不会被删除的, 只会影响DOM属性的值.

比如将一个input元素的readonly元素属性去掉,会导致对应的DOM属性变成false(即input变成可编辑状态):

$("#inputTest").removeAttr("readonly");

六,修改CSS样式
修改元素的样式, 我们可以修改元素CSS类或者直接修改元素的样式.

一个元素可以应用多个css类, 但是不幸的是在DOM属性中是用一个以空格分割的字符串存储的, 而不是数组. 所以如果在原始javascript时代我们想对元素添加或者删除多个属性时, 都要自己操作字符串.

jQuery让这一切变得异常简单. 我们再也不用做那些无聊的工作了.

1. 修改CSS类
下表是修改CSS类相关的jQuery方法:
名称 说明 实例

addClass( classes )

为每个匹配的元素添加指定的类名。 为匹配的元素加上 'selected' 类:
$("p").addClass("selected");
hasClass( class ) 判断包装集中是否至少有一个元素应用了指定的CSS类
$("p").hasClass("selected");
removeClass( [classes] ) 从所有匹配的元素中删除全部或者指定的类。 从匹配的元素中删除 'selected' 类:
$("p").removeClass("selected");
toggleClass( class ) 如果存在(不存在)就删除(添加)一个类。 为匹配的元素切换 'selected' 类:
$("p").toggleClass("selected");
toggleClass( class, switch ) 当switch是true时添加类,
当switch是false时删除类

每三次点击切换高亮样式:
var count = 0;
$("p").click(function(){
  $(this).toggleClass("highlight", count++ % 3 == 0);
});

使用上面的方法, 我们可以将元素的CSS类像集合一样修改, 再也不必手工解析字符串.

注意  addClass( class ) removeClass( [classes] ) 的参数可以一次传入多个css类, 用空格分割,比如:

$(<SPAN class=str>"#btnAdd"</SPAN>).bind(<SPAN class=str>"click"</SPAN>, <SPAN class=kwrd>function</SPAN>(<SPAN class=kwrd>event</SPAN>) { $(<SPAN class=str>"p"</SPAN>).addClass(<SPAN class=str>"colorRed borderBlue"</SPAN>); });


removeClass方法的参数可选, 如果不传入参数则移除全部CSS类:

 $(<SPAN class=str>"p"</SPAN>).removeClass()

 

2. 修改CSS样式

同样当我们想要修改元素的具体某一个CSS样式,即修改元素属性"style"时,  jQuery也提供了相应的方法:

名称 说明 实例
css( name ) 访问第一个匹配元素的样式属性。 取得第一个段落的color样式属性的值:

$("p").css("color");

css( properties )

把一个“名/值对”对象设置为所有匹配元素的样式属性。

这是一种在所有匹配的元素上设置大量样式属性的最佳方式。

将所有段落的字体颜色设为红色并且背景为蓝色:
$("p").css({ color: "#ff0011", background: "blue" });

css( name, value )

在所有匹配的元素中,设置一个样式属性的值。

数字将自动转化为像素值

将所有段落字体设为红色:

$("p").css("color","red");

 

七.获取常用属性

虽然我们可以通过获取属性,特性以及CSS样式来取得元素的几乎所有信息,  但是注意下面的实验:

<SPAN class=kwrd><!</SPAN><SPAN class=html>DOCTYPE</SPAN> <SPAN class=attr>html</SPAN> <SPAN class=attr>PUBLIC</SPAN> <SPAN class=kwrd>"-//W3C//DTD XHTML 1.0 Transitional//EN"</SPAN> <SPAN class=kwrd>"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"</SPAN><SPAN class=kwrd>></SPAN>
<SPAN class=kwrd><</SPAN><SPAN class=html>html</SPAN> <SPAN class=attr>xmlns</SPAN><SPAN class=kwrd>="http://www.w3.org/1999/xhtml"</SPAN><SPAN class=kwrd>></SPAN>
<SPAN class=kwrd><</SPAN><SPAN class=html>head</SPAN><SPAN class=kwrd>></SPAN>
  <SPAN class=kwrd><</SPAN><SPAN class=html>title</SPAN><SPAN class=kwrd>></SPAN>获取对象宽度<SPAN class=kwrd></</SPAN><SPAN class=html>title</SPAN><SPAN class=kwrd>></SPAN>
  <SPAN class=kwrd><</SPAN><SPAN class=html>script</SPAN> <SPAN class=attr>type</SPAN><SPAN class=kwrd>="text/javascript"</SPAN> <SPAN class=attr>src</SPAN><SPAN class=kwrd>="scripts/jquery-1.3.2-vsdoc2.js"</SPAN><SPAN class=kwrd>></</SPAN><SPAN class=html>script</SPAN><SPAN class=kwrd>></SPAN>
  <script type=<SPAN class=str>"text/javascript"</SPAN>>
    $(<SPAN class=kwrd>function</SPAN>()
    {
      alert(<SPAN class=str>"attr(\"width\"):"</SPAN> + $(<SPAN class=str>"#testDiv"</SPAN>).attr(<SPAN class=str>"width"</SPAN>)); <SPAN class=rem>//undifined</SPAN>
      alert(<SPAN class=str>"css(\"width\"):"</SPAN> + $(<SPAN class=str>"#testDiv"</SPAN>).css(<SPAN class=str>"width"</SPAN>)); <SPAN class=rem>//auto(ie6) 或 1264px(ff)</SPAN>
      alert(<SPAN class=str>"width():"</SPAN> + $(<SPAN class=str>"#testDiv"</SPAN>).width()); <SPAN class=rem>//正确的数值1264</SPAN>
      alert(<SPAN class=str>"style.width:"</SPAN> + $(<SPAN class=str>"#testDiv"</SPAN>)[0].style.width ); <SPAN class=rem>//空值</SPAN>
    })
  <SPAN class=kwrd></</SPAN><SPAN class=html>script</SPAN><SPAN class=kwrd>></SPAN>
<SPAN class=kwrd></</SPAN><SPAN class=html>head</SPAN><SPAN class=kwrd>></SPAN>
<SPAN class=kwrd><</SPAN><SPAN class=html>body</SPAN><SPAN class=kwrd>></SPAN>
  <SPAN class=kwrd><</SPAN><SPAN class=html>div</SPAN> <SPAN class=attr>id</SPAN><SPAN class=kwrd>="testDiv"</SPAN><SPAN class=kwrd>></SPAN>
    测试文本<SPAN class=kwrd></</SPAN><SPAN class=html>div</SPAN><SPAN class=kwrd>></SPAN>
<SPAN class=kwrd></</SPAN><SPAN class=html>body</SPAN><SPAN class=kwrd>></SPAN>
<SPAN class=kwrd></</SPAN><SPAN class=html>html</SPAN><SPAN class=kwrd>></SPAN>


我们希望获取测试图层的宽度,  使用attr方法获取"元素特性"为undifined, 因为并没有为div添加width. 而使用css()方法虽然可以获取到style属性的值, 但是在不同浏览器里返回的结果不同, IE6下返回auto, 而FF下虽然返回了正确的数值但是后面带有"px". 所以jQuery提供了width()方法, 此方法返回的是正确的不带px的数值.

针对上面的问题, jQuery为常用的属性提供了获取和设置的方法, 比如width()用户获取元素的宽度, 而 width(val)用来设置元素宽度.

下面这些方法可以用来获取元素的常用属性值:

1.宽和高相关 Height and Width

名称 说明 举例
height( ) 取得第一个匹配元素当前计算的高度值(px)。 获取第一段的高:
$("p").height();
height( val ) 为每个匹配的元素设置CSS高度(hidth)属性的值。如果没有明确指定单位(如:em或%),使用px。 把所有段落的高设为 20:

$("p").height(20);

width( ) 取得第一个匹配元素当前计算的宽度值(px)。 获取第一段的宽:
$("p").width();
width( val )

为每个匹配的元素设置CSS宽度(width)属性的值。

如果没有明确指定单位(如:em或%),使用px。

将所有段落的宽设为 20:

$("p").width(20);

innerHeight( )

获取第一个匹配元素内部区域高度(包括补白、不包括边框)。
此方法对可见和隐藏元素均有效。

见最后示例
innerWidth( )

获取第一个匹配元素内部区域宽度(包括补白、不包括边框)。
此方法对可见和隐藏元素均有效。

见最后示例
outerHeight( [margin] )

获取第一个匹配元素外部高度(默认包括补白和边框)。
此方法对可见和隐藏元素均有效。

见最后示例
outerWidth( [margin] )

获取第一个匹配元素外部宽度(默认包括补白和边框)。
此方法对可见和隐藏元素均有效。

见最后示例

 

关于在获取长宽的函数中, 要区别"inner", "outer"和height/width这三种函数的区别:

image

outerWith可以接受一个bool值参数表示是否计算margin值.

相信此图一目了然各个函数所索取的范围. 图片以width为例说明的, height的各个函数同理. 

2.位置相关 Positioning

另外在一些设计套弹出对象的脚本中,常常需要动态获取弹出坐标并且设置元素的位置.

但是很多的计算位置的方法存在着浏览器兼容性问题,  jQuery中为我们提供了位置相关的各个函数:

名称 说明 举例
offset( )

获取匹配元素在当前窗口的相对偏移。

返回的对象包含两个整形属性:top 和 left。此方法只对可见元素有效。

获取第二段的偏移:
var p = $("p:last"); <br>var offset = p.offset(); <br>p.html( "left: " + offset.left + ", top: " + offset.top );
position( )

获取匹配元素相对父元素的偏移。

返回的对象包含两个整形属性:top 和 left。为精确计算结果,请在补白、边框和填充属性上使用像素单位。此方法只对可见元素有效。

获取第一段的偏移:
var p = $("p:first"); <br>var position = p.position(); <br>$("p:last").html( "left: " + position.left + ", top: " + position.top );
scrollTop( )

获取匹配元素相对滚动条顶部的偏移。

此方法对可见和隐藏元素均有效。

获取第一段相对滚动条顶部的偏移:
var p = $("p:first"); <br>$("p:last").text( "scrollTop:" + p.scrollTop() );
scrollTop( val )

传递参数值时,设置垂直滚动条顶部偏移为该值。

此方法对可见和隐藏元素均有效。

设定垂直滚动条值:
<code>$("div.demo").scrollTop(300);</code>
scrollLeft( )

获取匹配元素相对滚动条左侧的偏移。

此方法对可见和隐藏元素均有效。

获取第一段相对滚动条左侧的偏移:
var p = $("p:first"); <br>$("p:last").text( "scrollLeft:" + p.scrollLeft() );
scrollLeft( val )

传递参数值时,设置水平滚动条左侧偏移为该值。

此方法对可见和隐藏元素均有效。

设置相对滚动条左侧的偏移:
<code>$("div.demo").scrollLeft(300);</code>

 

八.总结

本篇文章主要讲解如何使用jQuery操作元素的属性和修改样式. 请大家主要注意元素属性和DOM属性的区别. 下一篇文章将讲解最重要的事件, 介绍如何绑定事件, 操作事件对象等.
作者:张子秋
出处:http://www.cnblogs.com/zhangziqiu/

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
在JavaFX中,有哪些不同的路径元素?在JavaFX中,有哪些不同的路径元素?Aug 28, 2023 pm 12:53 PM

javafx.scene.shape包提供了一些类,您可以使用它们绘制各种2D形状,但这些只是原始形状,如直线、圆形、多边形和椭圆形等等...因此,如果您想绘制复杂的自定义形状,您需要使用Path类。Path类Path类使用此表示形状的几何轮廓您可以绘制自定义路径。为了绘制自定义路径,JavaFX提供了各种路径元素,所有这些都可以作为javafx.scene.shape包中的类使用。LineTo-该类表示路径元素line。它可以帮助您从当前坐标到指定(新)坐标绘制一条直线。HlineTo-这是表

C++程序:向数组中添加一个元素C++程序:向数组中添加一个元素Aug 25, 2023 pm 10:29 PM

数组是一种线性顺序数据结构,用于在连续的内存位置中保存同质数据。与其他数据结构一样,数组也必须具备以某种有效方式插入、删除、遍历和更新元素的功能。在C++中,我们的数组是静态的。C++中还提供了一些动态数组结构。对于静态数组,该数组内可能存储Z个元素。到目前为止,我们已经有n个元素了。在本文中,我们将了解如何在C++中在数组末尾插入元素(也称为追加元素)。通过示例理解概念‘this’关键字的使用方式如下GivenarrayA=[10,14,65,85,96,12,35,74,69]Afterin

html5不支持哪些元素html5不支持哪些元素Aug 11, 2023 pm 01:25 PM

html5不支持的元素有纯表现性元素、基于框架的元素、应用程序元素、可替换元素和旧的表单元素。详细介绍:1、纯表现性的元素,如font、center、s、u等,这些元素通常被用于控制文本样式和布局;2、基于框架的元素,如frame、frameset和noframes,这些元素在过去用于创建网页布局和分割窗口;3、应用程序相关的元素,如applet和isinde等等。

jquery怎么移除 元素jquery怎么移除 元素Feb 17, 2023 am 09:49 AM

jquery移除元素的方法:1、通过jQuery remove()方法删除被选元素及其子元素,语法是“$("#div1").remove();”;2、通过jQuery empty()方法删除被选元素的子元素,语法是“$("#div1").empty();”。

如何使用HTML和CSS实现一个具有固定导航菜单的布局如何使用HTML和CSS实现一个具有固定导航菜单的布局Oct 26, 2023 am 11:02 AM

如何使用HTML和CSS实现一个具有固定导航菜单的布局在现代网页设计中,固定导航菜单是常见的布局之一。它可以使导航菜单始终保持在页面顶部或侧边,使用户可以方便地浏览网页内容。本文将介绍如何使用HTML和CSS实现一个具有固定导航菜单的布局,并提供具体的代码示例。首先,需要创建一个HTML结构来呈现网页的内容和导航菜单。以下是一个简单的示例

Python程序用于测试列表中的所有元素是否最大间隔为KPython程序用于测试列表中的所有元素是否最大间隔为KAug 28, 2023 pm 05:25 PM

在许多编程场景中,我们都会遇到需要确定列表中的所有元素是否最多相距K个位置的情况。这个问题出现在各个领域,例如数据分析、序列处理和算法挑战。能够测试和验证这些条件对于确保我们程序的完整性和正确性至关重要。在本文中,我们将探索一个Python程序来有效地解决这个问题。我们将讨论这个概念,提出解决问题的分步方法,并提供工作代码实现。读完本文后,您将清楚地了解如何使用Python检查列表中的元素是否最多相距K个位置。理解问题在深入研究解决方案之前,让我们首先详细了解问题陈述。给定一个元素列表,我们需要

Vue3中的ref函数详解:直接访问组件元素的应用Vue3中的ref函数详解:直接访问组件元素的应用Jun 18, 2023 am 11:51 AM

在Vue3中,ref函数是非常有用的,在开发过程中提供了很方便的操作方式。它允许直接访问Vue组件元素并对其进行操作。ref函数是一个创建一个被响应式地绑定的对象的函数。可以在Vue组件中使用它来引用一个元素或子组件,并从父组件操作这些元素或子组件。ref函数返回一个响应式的对象,并通过该对象暴露指定元素或子组件的引用。因此,可以通过该对象直接访问元素或子组

如何在Java中删除ArrayList的所有元素?如何在Java中删除ArrayList的所有元素?Sep 20, 2023 pm 02:21 PM

List接口扩展了Collection接口并存储元素序列。List接口提供了两种方法来有效地在列表中的任意点插入和删除多个元素。与集合不同,列表允许重复元素,如果列表中允许空值,则允许多个空值。List提供了add、remove方法来添加/删除元素。为了清除列表或从列表中删除所有元素,我们可以使用List的clear()方法。我们也可以使用removeAll()方法来达到与clear()方法相同的效果。在本文中,我们将通过相应的示例介绍clear()和removeAll()方法。语法-clear

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.