批改状态:合格
老师批语:
2018年4月4日作业要求
1.将attr()和css()方法的完整用法,以及快捷方法:width(),height(),offset(),position()..全部用实例进行演示,并发布到博客中….
2. 手写css()方法的用法,特别是参数语法要注意
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>1.属性与自定义属性操作:attr()和removeAttr()</title>
<style>
img{
width:300;
height:300;
border-radius: 50%;
box-shadow:5px 5px 5px #888
}
</style>
</head>
<body>
<img src="../images/zly.jpg" width="300" alt="美女" title="明星" id="pic" data-nation="中国">
</body>
</html>
<script type="text/javascript" src="../js/jquery-3.3.1.js"></script>
<script type="text/javascript">
/*预备知识: 读取器,设置器
1. 有一些函数,可以根据参数的数量不同,执行不同的功能,返回不同的值,类似于功能重载
2. 传入一个参数,执行读取操作getter,返回该参数的当前值,叫:读取器/获取器
3. 传入二个参数,执行赋值操作setter,修改当前参数的值,叫:设置器/修改器
4. 这种根据参数个数决定执行操作类型的方法,在jQuery中非常多,大家要留意
*/
// 1. attr():元素属性的获取与设置
//必须传参,以下这句,在console.log(res)中可以看到出错信息
//var res = $('img').attr()
//单参数为获取:可获取当前属性的值
//var res = $('#pic').attr('src')
//双参数为获取,第一个是属性名,第二个是要设置的新值
//$('#pic').attr('src', '../images/boy.jpeg')
//$('#pic').attr('style', 'border-radius: 50%;box-shadow:2px 2px 2px #888')
// 由此可见,attr()是典型的集读取器与设置器二合一的方法
//attr()可以获取到元素的自定义属性
//html5中,可以通过data-前缀给标签添加用户自定义属性
var res = $('#pic').attr('data-nation')
//attr()的属性值,还支持回调函数
$('#pic').attr('width', function(){return 100+50})
//注意: 回调返回的数值类型,会自动转为字符类型再赋值给width属性
var res = $('#pic').attr('width')
$('#pic').width(+=100)//本行实现了宽度自加100的效果
$('#pic').height(+=100)//
//2. removeAttr():删除元素的属性
//删除图片的内联样式属性style
//$('#pic').removeAttr('style')
//可以删除多个属性,多个属性之间用空格分开,返回当前元素的状态
var res = $('#pic').removeAttr('alt title data-nation')
//在控制台查看运行结果
console.log(res)
</script>点击 "运行实例" 按钮查看在线实例
未完待续
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号