博主信息
墨雨的博客
博文
46
粉丝
3
评论
2
访问量
22525
积分:1
P豆:342.53

jQuery属性操作attr()及内联样式操作CSS() 2018年4月4日

2018年04月09日 16:33:18阅读数:862博客 / 墨雨的博客/ PHP中文网2期培训班作业
  1. attr() 读取和设置属性,参数不可缺省。单参数读取属性值,双参数设置属性值。

实例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>jquery属性操作-attr()方法</title>
<style type="text/css">
		button{
		margin: 2px;
		}
</style>

</head>
<body>
	<img src="images/gyy.jpg" width="300" alt="高圆圆" title="美女" id="pic"><br>
	<button>读取img的width属性</button><br>
	<button>设置img的style属性(圆形)</button><br>
	<button>用函数设置img的width属性缩小或扩大50px</button><br>
	<button>用removeAttr()方法删除img的title属性</button>

</body>
</html>
<script type="text/javascript" src="../jquery-3.3.1.js"></script>
<script type="text/javascript">
		
	var l1 = $('#pic').attr('width')
	
	$('button').eq(0).click(function(){
		alert('照片宽度:' +l1+'px')
	})
	$('button').eq(1).click(function(){
		$("#pic").attr('style','border-radius:50%')
	})
	$('button').eq(2).click(function(){
	    if(l1==300){
			$('#pic').attr('width',function(){return l1-50})
			l1-=50
	    }else{
	    	$('#pic').attr('width',function(){return l1+50})
	    	l1+=50
	    }
	})
	$('button').eq(3).click(function(){
		$("#pic").removeAttr("title")
	})
</script>

运行实例 »

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

2.CSS()读取和设置内联样式。语法和attract()大致一样,宽高的读取和设置可用简写方式width()、height(),元素偏移量相对于文本和相对于父元素可分别用offset()h和position()

实例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>jQuery内联样式操作</title>
	<style type="text/css">
		.box1 {
			width: 300px;
			height: 300px;
			background-color: wheat;
			position: relative;
		}
		.box2 {
			width: 100px;
			height: 100px;
			background-color: coral;
			position: absolute;
			top: 50px;
			left: 100px;
		}
		button{
		margin: 2px;
		}
	</style>
</head>
<body>
	<img src="images/gyy.jpg" width="200">
	<div class="box1">
		<div class="box2"></div>
	</div><br>
	<button>CSS(name)读取样式</button><br>
	<button>CSS(name,value)设置样式</button><br>
	<button>CSS()的简写width()、height()设置宽高</button><br>
	<button>offset()查询相对于文本的偏移量</button><br>
	<button>position()查看相对于父元素的偏移量</button>
</body>
</html>
<script type="text/javascript" src="../jquery-3.3.1.js"></script>
<script type="text/javascript">
	$('button').eq(0).click(function(){
		alert('img元素的width属性是'+$('img').css('width'))
	})
	$('button').eq(1).click(function(){
		$('img').css({'border-radius':'50%','box-shadow':'3px 3px 3px #888'})
	})
	$('button').eq(2).click(function(){
		$('img').width('+=100')
	})
	//height()方法与width()完全一致
	$('button').eq(3).click(function(){
		var l = $('img').offset().left
		var t = $('img').offset().top
		alert('img元素相对于body的偏移量: 左 '+l+' 上 '+t)
	})
	$('button').eq(4).click(function(){
		var l = $('.box2').position().left
		var t = $('.box2').position().top
		alert('box2相对于box1的偏移量: 左 '+l+' 上 '+t)
	})
</script>

运行实例 »

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

jQuery内联样式操作CSS()练习手抄代码

IMG_20180409_161202.jpgIMG_20180409_161211.jpg

批改状态:未批改

老师批语:

版权申明:本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!

全部评论

文明上网理性发言,请遵守新闻评论服务协议

条评论