JavaScript中event详解

原文地址:http://www.blogjava.net/swingboat/archive/2006/02/23/32064.html,本文重新对其进行了编辑和排版。


event代表事件的状态,例如触发event对象的元素、鼠标的位置及状态、按下的键等等。
event对象只在事件发生的过程中才有效。
event的某些属性只对特定的事件有意义。比如,fromElement 和 toElement 属性只对 onmouseover 和 onmouseout 事件有意义。

例子

下面的例子检查鼠标是否在链接上单击,并且,如果shift键被按下,就取消链接的跳转。

[html]  view plain copy
  1. <HEAD><TITLE>Cancels Links</TITLE>  
  2. <SCRIPT LANGUAGE="JScript">  
  3. function cancelLink() {  
  4.     if (window.event.srcElement.tagName == "A" && window.event.shiftKey)  
  5.     window.event.returnValue = false;  
  6. }  
  7. </SCRIPT></HEAD>  
  8. <BODY onclick="cancelLink()" />  

下面的例子在状态栏上显示鼠标的当前位置。

[html]  view plain copy
  1. <BODY onmousemove="window.status = 'X=' + window.event.x + ' Y=' + window.event.y">  

属性:

altKey, button, cancelBubble, clientX, clientY, ctrlKey, fromElement, keyCode, offsetX, offsetY, propertyName, returnValue, screenX, 
screenY, shiftKey, srcElement, srcFilter, toElement, type, x, y

1.altKey

描述:
检查alt键的状态。

语法:
event.altKey

可能的值:
当alt键按下时,值为 TRUE ,否则为 FALSE 。只读。

2.button

描述:
检查按下的鼠标键。

语法:
event.button

可能的值:
0 没按键
1 按左键
2 按右键
3 按左右键
4 按中间键
5 按左键和中间键
6 按右键和中间键
7 按所有的键

这个属性仅用于onmousedown, onmouseup, 和 onmousemove 事件。对其他事件,不管鼠标状态如何,都返回 0(比如onclick)。

3.cancelBubble

描述:
检测是否接受上层元素的事件的控制。

语法:
event.cancelBubble[ = cancelBubble]

可能的值:
这是一个可读写的布尔值:

TRUE 不被上层原素的事件控制。
FALSE 允许被上层元素的事件控制。这是默认值。

例子:
下面的代码片断演示了当在图片上点击(onclick)时,如果同时shift键也被按下,就取消上层元素(body)上的事件onclick所引发的showSrc()函数。

[html]  view plain copy
  1. <SCRIPT LANGUAGE="JScript">  
  2. function checkCancel() {  
  3.     if (window.event.shiftKey)  
  4.     window.event.cancelBubble = true;  
  5. }  
  6. function showSrc() {  
  7.     if (window.event.srcElement.tagName == "IMG")  
  8.     alert(window.event.srcElement.src);  
  9. }  
  10. </SCRIPT>  
  11. <BODY onclick="showSrc()">  
  12. <IMG onclick="checkCancel()" SRC="sample.gif">  

4.clientX

描述:
返回鼠标在窗口客户区域中的X坐标。

语法:
event.clientX

注释:
这是个只读属性。这意味着,你只能通过它来得到鼠标的当前位置,却不能用它来更改鼠标的位置。

5.clientY

描述:
返回鼠标在窗口客户区域中的Y坐标。

语法:
event.clientY

注释:
这是个只读属性。这意味着,你只能通过它来得到鼠标的当前位置,却不能用它来更改鼠标的位置。

6.ctrlKey

描述:
检查ctrl键的状态。

语法:
event.ctrlKey

可能的值:
当ctrl键按下时,值为 TRUE ,否则为 FALSE 。只读。

7.fromElement

描述:
检测 onmouseover 和 onmouseout 事件发生时,鼠标所离开的元素。 参考:18.toElement

语法:
event.fromElement

注释:
这是个只读属性。

8.keyCode

描述:
检测键盘事件相对应的内码。
这个属性用于 onkeydown, onkeyup, 和 onkeypress 事件。

语法:
event.keyCode[ = keyCode]

可能的值:
这是个可读写的值,可以是任何一个Unicode键盘内码。如果没有引发键盘事件,则该值为 0 。

9.offsetX

描述:
检查相对于触发事件的对象,鼠标位置的水平坐标

语法:
event.offsetX

10.offsetY

描述:
检查相对于触发事件的对象,鼠标位置的垂直坐标

语法:
event.offsetY

11.propertyName

描述:
设置或返回元素的变化了的属性的名称。

语法:
event.propertyName [ = sProperty ]

可能的值:
sProperty 是一个字符串,指定或返回触发事件的元素在事件中变化了的属性的名称。
这个属性是可读写的。无默认值。

注释:
你可以通过使用 onpropertychange 事件,得到 propertyName 的值。

例子:
下面的例子通过使用 onpropertychange 事件,弹出一个对话框,显示 propertyName 的值。

[html]  view plain copy
  1. <HEAD>  
  2. <SCRIPT>  
  3. function changeProp(){  
  4.     btnProp.value = "This is the new VALUE";  
  5. }  
  6. function changeCSSProp(){  
  7.     btnStyleProp.style.backgroundColor = "aqua";  
  8. }  
  9. </SCRIPT>  
  10. </HEAD>  
  11. <BODY>  
  12. <P>The event object property propertyName is  
  13. used here to return which property has been  
  14. altered.</P>  
  15. <INPUT TYPE=button ID=btnProp onclick="changeProp()"  
  16. VALUE="Click to change the VALUE property of this button"  
  17. onpropertychange='alert(event.propertyName+" property has changed value")'>  
  18. <INPUT TYPE=button ID=btnStyleProp  
  19. onclick="changeCSSProp()"  
  20. VALUE="Click to change the CSS backgroundColor property of this button"  
  21. onpropertychange='alert(event.propertyName+" property has changed value")'>  
  22. </BODY>  

12.returnValue

描述:
设置或检查从事件中返回的值

语法:
event.returnValue[ = Boolean]

可能的值:
true 事件中的值被返回
false 源对象上事件的默认操作被取消

例子见本文的开头。

13.screenX

描述:
检测鼠标相对于用户屏幕的水平位置

语法:
event.screenX

注释:
这是个只读属性。这意味着,你只能通过它来得到鼠标的当前位置,却不能用它来更改鼠标的位置。

14.screenY

描述:
检测鼠标相对于用户屏幕的垂直位置

语法:
event.screenY

注释:
这是个只读属性。这意味着,你只能通过它来得到鼠标的当前位置,却不能用它来更改鼠标的位置。

15.shiftKey

描述:
检查shift键的状态。

语法:
event.shiftKey

可能的值:
当shift键按下时,值为 TRUE ,否则为 FALSE 。只读。

16.srcElement

描述:
返回触发事件的元素。只读。例子见本文开头。

语法:
event.srcElement

17.srcFilter

描述:
返回触发 onfilterchange 事件的滤镜。只读。

语法:
event.srcFilter

18.toElement

描述:
检测 onmouseover 和 onmouseout 事件发生时,鼠标所进入的元素。 参考:7.fromElement

语法:
event.toElement

注释:
这是个只读属性。

例子:下面的代码演示了当鼠标移到按钮上时,弹出一个对话框,显示“mouse arrived”

[html]  view plain copy
  1. <SCRIPT>  
  2. function testMouse(oObject) {  
  3.     if(oObject.contains(event.toElement)) {  
  4.         alert("mouse arrived");  
  5.     }  
  6. }  
  7. </SCRIPT>  
  8. <BUTTON ID=oButton onmouseover="testMouse(this)">Mouse Over This.</BUTTON>  

19.type

描述:
返回事件名。

语法:
event.type

注释:
返回没有“on”作为前缀的事件名,比如,onclick事件返回的type是click
只读。

20. x

描述:
返回鼠标相对于css属性中有position属性的上级元素的x轴坐标。如果没有css属性中有position属性的上级元素,默认以BODY元素作为参考对象。

语法:
event.x

注释:
如果事件触发后,鼠标移出窗口外,则返回的值为 -1
这是个只读属性。这意味着,你只能通过它来得到鼠标的当前位置,却不能用它来更改鼠标的位置。

21. y

描述:
返回鼠标相对于css属性中有position属性的上级元素的y轴坐标。如果没有css属性中有position属性的上级元素,默认以BODY元素作为参考对象。

语法:
event.y

注释:
如果事件触发后,鼠标移出窗口外,则返回的值为 -1
这是个只读属性。这意味着,你只能通过它来得到鼠标的当前位置,却不能用它来更改鼠标的位置。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Element UI 的 Upload 组件是一个文件上传组件,允许用户上传多个文件,并支持拖拽上传和文件预览。下面我将详细介绍这个组件的使用方法。 ## 安装 首先,需要在项目安装 Element UI。 ```bash npm install element-ui --save ``` 然后,在 main.js 引入 Element UI。 ```javascript import Vue from 'vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI) ``` ## 基本用法 在需要使用 Upload 的组件,可以这样写: ```html <el-upload class="upload-demo" action="/upload" :data="{ user_id: 123 }" :on-success="handleSuccess" :on-error="handleError" :before-upload="beforeUpload" :file-list="fileList" :auto-upload="false"> <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <el-button size="small" type="success" @click="submitUpload">上传到服务器</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> ``` 上面代码,`action` 属性是上传的后端接口地址,`data` 属性是上传时需要携带的额外参数,`on-success` 和 `on-error` 属性分别是上传成功和失败时的回调函数,`before-upload` 属性是上传前的校验函数,`file-list` 属性是已经上传的文件列表,`auto-upload` 属性表示是否自动上传。 在 Upload 组件,需要通过 `slot` 分别定义两个按钮,分别是选取文件和上传到服务器的按钮。同时,可以通过 `slot` 定义提示信息。 ```html <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <el-button size="small" type="success" @click="submitUpload">上传到服务器</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> ``` 最后,需要在 Vue 实例定义对应的函数。 ```javascript export default { data() { return { fileList: [] } }, methods: { handleSuccess(response, file, fileList) { console.log(response, file, fileList); }, handleError(error, file, fileList) { console.log(error, file, fileList); }, beforeUpload(file) { const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG 格式!'); } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!'); } return isJPG && isLt2M; }, submitUpload() { this.$refs.upload.submit(); } } } ``` 上面代码,`handleSuccess` 和 `handleError` 分别是上传成功和失败时的回调函数,在这里可以对上传的结果进行处理。`beforeUpload` 是上传前的校验函数,可以在这里对上传的文件进行校验。`submitUpload` 用于手动触发上传。 ## 高级用法 ### 限制上传文件类型和大小 可以通过 `accept` 和 `before-upload` 属性来限制上传文件的类型和大小。 ```html <el-upload class="upload-demo" action="/upload" :data="{ user_id: 123 }" :on-success="handleSuccess" :on-error="handleError" :before-upload="beforeUpload" :file-list="fileList" :auto-upload="false" accept="image/*" :limit="3" :on-exceed="handleExceed"> <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <el-button size="small" type="success" @click="submitUpload">上传到服务器</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> ``` 上面代码,`accept` 属性限制了只能上传图片类型的文件,`before-upload` 函数限制了文件大小不超过 500KB,同时还设置了最多上传 3 个文件的限制,并在超出限制时触发 `on-exceed` 方法。 ```javascript handleExceed(files, fileList) { this.$message.warning(`当前限制选择 ${this.limit} 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`); } ``` ### 上传到阿里云 OSS 可以通过 `before-upload` 和 `custom-request` 属性来实现上传到阿里云 OSS。 ```html <el-upload class="upload-demo" :action="ossConfig.host" :data="ossConfig.params" :on-success="handleSuccess" :on-error="handleError" :before-upload="beforeUpload" :file-list="fileList" :auto-upload="false" :custom-request="ossConfig.customRequest"> <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <el-button size="small" type="success" @click="submitUpload">上传到服务器</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> ``` 上面代码,`action` 属性设置为阿里云 OSS 的上传地址,`data` 属性设置为上传时需要携带的额外参数。在 `before-upload` 函数,需要返回一个 Promise 对象,该 Promise 对象需要实现上传到阿里云 OSS 的逻辑。 ```javascript beforeUpload(file) { const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG 格式!'); } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!'); } return isJPG && isLt2M && new Promise((resolve, reject) => { const ossConfig = this.getOssConfig(); this.ossConfig = ossConfig; const client = new OSS({ accessKeyId: ossConfig.accessid, accessKeySecret: ossConfig.accesskey, stsToken: ossConfig.securitytoken, bucket: ossConfig.bucket, region: ossConfig.region, cname: true }); client.multipartUpload(ossConfig.dir + '/' + file.name, file).then((result) => { console.log(result); resolve(); }).catch((error) => { console.log(error); reject(); }); }); }, getOssConfig() { // 获取阿里云 OSS 的配置 } ``` 在 `custom-request` 函数,可以实现上传成功和失败的回调函数。 ```javascript ossConfig: { host: '', params: {}, customRequest: (config) => { const { action, data, file, headers, onError, onSuccess, onProgress } = config; const xhr = new XMLHttpRequest(); xhr.open('POST', action, true); Object.keys(headers).forEach((key) => { xhr.setRequestHeader(key, headers[key]); }); xhr.onload = function onload() { if (xhr.readyState === 4 && xhr.status === 200 && xhr.responseText !== '') { try { const response = JSON.parse(xhr.responseText); onSuccess(response, xhr); } catch (error) { onError(error, xhr); } } else { onError(new Error('上传失败'), xhr); } }; xhr.onerror = function onerror(error) { onError(error, xhr); }; xhr.upload.onprogress = function onprogress(event) { if (event.total > 0) { event.percent = (event.loaded / event.total) * 100; } onProgress(event, xhr); }; const formData = new FormData(); Object.keys(data).forEach((key) => { formData.append(key, data[key]); }); formData.append('file', file); xhr.send(formData); } }, ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值