在jQuery中可以使用css()和attr()方法来获取css样式属性的值。css() 方法设置或返回被选元素的一个或多个样式属性;attr() 方法设置或返回被选元素的属性和值。
jQuery css()方法
css() 方法设置或返回被选元素的一个或多个样式属性。
返回CSS属性的值
$(selector).css("propertyname");示例:将返回首个匹配元素的 background-color值:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("背景颜色 = " + $("p").css("background-color"));
});
});
</script>
</head>
<body>
<h2>这是一个标题</h2>
<p style="background-color:#ff0000">这是一个段落。</p>
<p style="background-color:#00ff00">这是一个段落。</p>
<p style="background-color:#0000ff">这是一个段落。</p>
<button>返回第一个 p 元素的 background-color </button>
</body>
</html>jQuery attr()方法
attr() 方法设置或返回被选元素的属性和值。当该方法用于返回属性值,则返回第一个匹配元素的值。
语法:
$(selector).attr(attribute)
示例:获得图像的width属性和height属性的值。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script>
<script>
$(document).ready(function() {
$("button").click(function() {
alert("图像的width值为: " +
$("img").attr("width")+"\n\n图像的height值为: " +
$("img").attr("height"));
});
});
</script>
</head>
<body>
<h2> jQuery attr() 方法</h2>
<h3 style="color:lightgreen;"></h3>
<img src= "1.jpg" width="600" height="300"/>
<br>
<br>
<button>Click</button>
</body>
</html>试试看吧!



网友评论文明上网理性发言 已有0人参与
发表评论: