博客列表 >0404作业-attr()和css()方法

0404作业-attr()和css()方法

唔良人
唔良人原创
2018年04月07日 19:42:28689浏览

实例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>attr()方法</title>
</head>
<body>
	<!-- html5中,可以通过data-前缀给标签添加用户自定义属性 -->
	<img src="https://img.php.cn/upload/avatar/000/000/001/bf7dc0465d67f3458bb72fe1656c9ec8.jpg" width="200" alt="头像" title="头像" id="pic" data-nation="英国">
</body>
</html>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
	//attr():元素属性的获取与设置
	//1.必须传参,不传参数报错
	// var res = $('img').attr()

	//2.一个参数,获取对应参数的值,可以是自定义属性
	var res = $('img').attr('title')
	var res = $('img').attr('alt')
	var res = $('img').attr('data-nation')

	//3.双参数为获取,第一个是属性名,第二个是要设置的新值
	var res = $('img').attr('title','女明星')
	$('#pic').attr('style', 'border-radius: 50%;box-shadow:2px 2px 2px #888')

	//4.attr()的属性值,还支持回调函数
	var res = $('img').attr('width',function(){return 100+100})

	// removeAttr():删除元素的属性
	// var res = $('img').removeAttr('title')
	var res = $('img').removeAttr('title alt data-nation')

	console.log(res)
</script>

运行实例 »

点击 "运行实例" 按钮查看在线实例

2.css()方法

实例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>内联样式css()</title>
	<style type="text/css">
		.box1{
			width: 200px;
			height: 200px;
			background-color: yellow;
			position: relative;
		}
		.box2{
			width: 100px;
			height: 100px;
			background-color: pink;
			position: absolute;
			top:50px;
			left: 20px;
		}
	</style>
</head>
<body>
	<img src="https://img.php.cn/upload/avatar/000/000/001/bf7dc0465d67f3458bb72fe1656c9ec8.jpg">
	<div class="box1">
		<div class="box2"></div>
	</div>	
</body>
</html>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
	//css()方法与attr()方法很相似,也是自带读到与设置特征
	//根据参数数量确定要执行的操作,一个参数是读取,二个参数是设置
	//功能相当于读到或设置当前元素的style属性的值,其实就是内联样式

	//1.设置样式 css(name,value)
	// var res = $('img').css('width',200)
	// var res = $('img').css('border-radius','50%')

	//同时设置多个属性
	var res = $('img').css({
		'width':200,
		'border-radius':'50%'
	})

	var res = $('img').css('width')
	var res = parseInt($('img').css('width'))
	res += 50
	var res = $('img').css('width',res+'px')

	// width()和height()方法
	var res = $('img').width()
	var res = $('img').width('-=50')

	var res = $('img').css('width','+=50')

	// 4.获取元素的位置:offset(),返回的是一个对象
	var res = $('img').offset()
	var res = $('img').offset().left
	var res = $('img').offset().top

	//5.查看绝对定位元素的偏移量: position()
	var res = $('.box2').position()
	var res = $('.box2').position().top
	var res = $('.box2').position().left

	console.log(res)
</script>

运行实例 »

点击 "运行实例" 按钮查看在线实例

1523102400752.jpg

1523102412230.jpg

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议