jq 事件函数练习
在 jquery 中是以调用事件函数的形式来触发事件
简单理解:事件方法会触发匹配元素的事件,或者将函数绑定到所有匹配元素的某个事件
ready()方法:文档对象模型DOM完全加载完后触发事件;相当于 js 的 onload 事件。
语法:
$(document).ready(function(){})
注意不可以跟<body onload="">一起使用。
blur()方法:当元素失去焦点时调用事件;相当于 js 中的 onblur。
举例:input 元素失去焦点后宽度变为100px:
$("input").blur(function () { $("input").css("width", "100px") })
focus()方法:当元素获得焦点时调用事件;相当于 js 中的 on focus。 效果与 blur()相反。
click()方法:元素被点击后触发事件。
举例:单击按钮弹窗:
$("button").click(function () { alert("按钮被点击了") })
dblclick()方法:元素被双击后触发事件;
mouseover()方法:鼠标指针位于元素上方时触发事件;
mouseenter()方法:鼠标指针穿过元素时触发事件;
不论鼠标指针穿过被选元素或其子元素,都会触发 mouseover 事件。对应mouseout
只有在鼠标指针穿过被选元素时,才会触发 mouseenter 事件。对应mouseleave
pageX()方法:获取鼠标的 x 坐标;
pageY()方法:获取鼠标的 Y 坐标;
resize()方法:调整浏览器大小时触发事件;
用上述所有方法做了一个案例:
改变窗口大小 div1背景变化
代码"
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="jquery-3.3.1.js"></script> <style> div { width: 200px; height: 200px; background: red; margin-bottom: 50px; /* border: 3px solid rgb(70, 70, 0); */ } .box1, .box2 { position: relative; left: 150px; width: 100px; height: 100px; background: rgb(25, 11, 221); margin-bottom: 20px; } </style> </head> <body> <script> $(document).ready(function () {//jq就绪函数 $(".div1").mouseenter(function () {//鼠标进入该元素,文字变化 $(".div1").html("鼠标穿过了这个元素,所以这里面的内容发生了变化") }) $(".div1").mousedown(function () {//鼠标在该元素按下,元素变小 $(".div1").css({ "width": "180px", "height": "180px" }) }) $(".div1").mouseup(function () {//鼠标在该元素抬起,元素变大 $(".div1").css({ "width": "250px", "height": "250px" }) }) $(".div1").mouseleave(function () {//鼠标离开该元素,元素背景色变绿 $(".div1").css("background", "green") }) $(document).mousemove(function (a) {//鼠标移动时获取鼠标坐标并输入到div2中 $("#div2").text("鼠标坐标是(" + a.pageX + "," + a.pageY + ")") }) $(window).resize(function () {//rgb设置随机颜色 $r = Math.floor(Math.random() * 256); $g = Math.floor(Math.random() * 256); $b = Math.floor(Math.random() * 256); $(".div1").css( "background", 'rgb(' + $r + ',' + $g + ',' + $b + ')' ) }) }) </script> <div class="div1"> 移动到上面文字发生变化,鼠标按下时该元素变小,抬起时变大 </div> <div id="div2"></div> </body> </html>