批改状态:合格
老师批语:
attr()和css()功能和用法基本相似,但attr()主要用于设置标签属性,css()主要用于设置style元素属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>attr()和css()及常见样式函数</title>
</head>
<style type="text/css">
.box{width:450px;height:250px;background: yellow;margin:0 auto;overflow: hidden}
.box1{width:250px;height:250px;background: green;float: left}
.box2{width:200px;height:200px;background: blue;float:left;}
</style>
<body>
<div class="box">
<div class="box1">
<img src="https://www.baidu.com/img/baidu_jgylogo3.gif">
</div>
<div class="box2"><p>这是一段文字</p></div>
</div>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
//利用attr()方法获取元素的固有属性
var attr=$('.box1 img').attr('src')
//利用attr()方法设置元素的属性
$('.box1 img').attr('src','http://www.news.cn/2014/images/xh_logo.png')
//利用attr()方法设置多个属性
$('.box1 img').attr({'width':'100%','border':'2px solid red'})
// console.log(attr)
//利用css()方法设置元素属性
$('.box2').css('background-color','lightgreen')
//利用css()方法查询元素属性
var c=$('.box2').css('background-color')
//利用css()方法设置多个属性
$('.box2 p').css({'background-color':'skyblue','color':'red','font-size':'20px'})
console.log(c)
//width()方法获取元素宽度属性
var w=$('.box').width()
console.log(w)
//同上,获取高度
var h=$('.box').height()
console.log(h)
//offset()获取偏移量
var o=$('.box').offset()
console.log(o)
//相对父元素偏移量
var p=$('.box').position()
console.log(p)
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
手抄

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号