批改状态:未批改
老师批语:
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()练习手抄代码


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