About the event
1. event binding
1.1 Basic Binding
// 单击与双击事件
$(element).click(function(){});
$(element).dblclick(function(){});
// 加载完毕事件
$(document).ready(function(){});
$(function(){});
1.2 Methods Binding
$(element).bind('click', function(){}); // 绑定事件
$(element).unbind(); // 解除事件绑定
1.3 Dynamic Binding
- Note: live in the method is removed from the high version (> 1.8.3) of jQuery, note the version to use
$(element).live('click', function(){});
2. Trigger Event
2.1 trigger wording
- When we want to trigger the event of an element, you can use
trigger
- Note: the elements required for the type of event
$(element).trigger('click'); // 必须指定元素的事件类型,如此处的 click
2.2 normal mouse event
Mouse click events |
click |
Mouse double-click event |
dbclick |
Mouse moved event |
mouseover |
Mouse out of the event |
mouseout |
Mouse press event |
mousedown |
Mouse lift Event |
mouseup |
Mouse movement events |
mousemove |
$('div').mousedown(function(){
console.log("鼠标被按下了");
});
3. The event bubbling and the default behavior
3.1 event bubbling
- When a triggering event elements, which automatically triggers the parent and ancestors level of the same type of event that element, resulting in concurrent events, leading to confusion page , an event we call the bubble
- At this point we can return one of the elements in the event handler
false
to prevent
- Note: This method is limited to use in jQuery
3.2 default behavior
- In the page, some elements that have default behavior, such as
- Click a link
- Form submission
- Jump or more elements will be submitted, these acts are called "default behavior"
- However, after binding on the event, it will first perform the first event, and then perform the default behavior
- If we just want to let the trigger event, but does not do default behavior, we can return in a event that element
false
to prevent the default behavior
<a href="https://www.cnblogs.com">点我去博客园</a>
$('a').click(function(){
alert("单击事件被触发了");
return false; // 阻止默认行为
});
4. obtain the current position of the mouse button depressed and
- We have mouse and keyboard events
- When the trigger event, if we want to get the mouse position or keyboard key information
- First, we need the current event passes an event object
event
$(element).click(function(e){
// e for enent,类似于在 Python 中写 Class 时要加 self
// 能够获取鼠标的 x 轴和 y 轴坐标,坐标位置相对于浏览器窗口
var x = e.clientX;
var y = e.clientY;
// 能够获取鼠标的 x 轴和 y 轴坐标,坐标位置相对于文档
var _x = e.pageX;
var _y = e.pageY;
});
$(element).keydown(function(e){
// 可以打印 e 对象,或者直接使用该对象中的 keyCode 属性来获取按键信息
var key = e.keyCode;
console.log(key);
});