jQuery基础
jQuery 是一个JavaScript 库,让开发者快速操作页面元素,实现交互。
jQuery基础–语法
- 基础语法是:$(selector).action()
- $为jQuery的别名(简写)
- 选择器(selector)“查询”和“查找”HTML 元素
- jQuery 的action() 执行对元素的操作
常用选择器:
- 标签选择器 p
- id选择器 #demo
- 类选择器 .demo
显示或者隐藏图片
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js" type="text/javascript"></script>
<title>Document</title>
</head>
<body>
<div>
<button id="button">显示/隐藏</button>
</div>
<img src="images/girl.jpg" class="demo" id="image" alt="图片加载不成功">
</body>
<script type="text/javascript">
$('#button').on('click',function(){
if ($('#image').is(':visible')){
// id选择器
$('#image').hide();
// 标签选择器
$('button').css("background",'red')
}else{
$('#image').show();
$('#button').css("background",'#bfa')
}
});
</script>
</html>
元素操作:
- 添加/替换:append() html()
- 隐藏/展示:show() fadeIn() hide() fadeOut()
- 删除: remove
$('#container')
n.fn.init [div#container, context: document, selector: "#container"]
$('#container').append('<p>hello</>')
n.fn.init [div#container, context: document, selector: "#container"]
$('p').hide()
n.fn.init [p, prevObject: n.fn.init(1), context: document, selector: "p"]
$('p').show()
n.fn.init [p, prevObject: n.fn.init(1), context: document, selector: "p"]
$('p').remove()
n.fn.init [p, prevObject: n.fn.init(1), context: d
常见的事件
- 点击:click
- 双击: dblclick
- 鼠标移上: mouseover
- 鼠标移开: mouseout
点击超链接显示提示,移开消失。
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<p><a href="#" class="demo" title="显示超链接1">超链接1.</a></p>
<p><a href="#" class="demo" title="显示超链接2">超链接2.</a></p>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(".demo").mouseover(function(e){
var title = $(this).attr('title');
var tooltip = "<div id='tooltip'>"+ title +"<\/div>"; //创建 div 元素
$("body").append(tooltip); //把它追加到文档中
$("#tooltip").css({
"top": e.pageY + "px",
"left": e.pageX + "px"
}).show("fast"); //设置x坐标和y坐标,并且显示
}).mouseout(function(){
$("#tooltip").remove(); //移除
});
</script>
</body>
</html>

浙公网安备 33010602011771号