例1.需求:现有内容为“aaaaaaa”的a标签,要求设置它的字体颜色为红色,点击之后为标签加上边框。
<a href="#">aaaaaaa</a>
(1)原生js写法
var a = document.getElementsByTagName('a')[0];
a.style.color = "red";
a.click = function(){
this.style.border = "10px solid #000";
};
(2)jquery写法(记得引入jquery.js文件)
//引入文件
<script src="jquery.js"></script>
var s = $('a');
a.css('color','red').click(function(){
$(this).css('border','10px solid #000');
});
例2.需求:现有一组p标签,要求点击每个p标签,弹出p标签里面的内容
<p>我是第1个p标签</p>
<p>我是第2个p标签</p>
<p>我是第3个p标签</p>
(1)原生js写法
var p = document.getElementsByTagName('p');
for(var i = 0; i<p/length; i++){
p[i].click = function(){
alert(this.innerHTML);
}
}
(2)jquery写法
var p = $('p');
p.click(function(){
alert($(this).html());
});
使用jQuery.noConflict();解决jQuery与其他js库冲突,与其他库共存。
jQuery事件
- 加载文档事件
- 鼠标事件
- 键盘事件
- 表单事件
- 浏览器事件
- 事件对象 event.pageX() ,event.pageY() ,event.preventDefault() ,event.stopPropagation() ,event.which
- 绑定和移除事件的方法bind() ,unbind() ,one() ,delegate() ,on() ,off()
- 事件命名空间unbind(‘click.background’)或者var space = {}
- hover() ,trigger(”)模拟事件发生,triggerHandler()
例3.jQuery的基础动画
<html>
<head>
<title>p标签的显示和隐藏</title>
<script src="jquery.js"></script>
</head>
<body>
<a href="#">点击</a>
<p>p标签</p>
<script>
$('a').click(function(){
$('p').toggle(600);
//toggle()三个效果参数(slow,fast,normal)或毫秒数
//show()和hide()方法参数同上。
});
</script>
</body>
</html>
例4.jQuery的渐变动画,滑动动画
<html>
<head>
<title>demo.html</title>
<script src="jquery.js"></script>
</head>
<body>
<a href="#">点击</a>
<p>p标签</p>
<script>
$('a').click(function(){
$('p').fadeIn(10);//效果:透明度opacity从0变成1
//fadeOut();
//fadeTo();参数slow,fast
//fadeToggle();
});
//以下是滑动动画
//slideDown();
//slideUp();
//slideToggle();
</script>
</body>
</html>
例5.jQuery的自定义动画animate
<html>
<head>
<title>demo.html</title>
<script src="jquery.js"></script>
<style>
div {
width: 100px;
height: 100px;
background: red;
position: absolute;
left: 0;
top: 50px;
}
</style>
</head>
<body>
<input type="button" value="点击">
<div></div>
<script>
$('input').click(function(){
$('div').animate(function(){
'left':'800px';
'top':'500px';
'opacity':'0.2';
},3000,function(){
$('div').css('background','#f90');
});
});
</script>
</body>
</html>
jquery的动画队列:stop() ,dequeue() ,finish() ,delay()