Javascript 模拟点击事件(点击链接与html点击) 兼容IE/Firefox_javascript技巧

WBOY
Release: 2016-05-16 18:37:25
Original
1887 people have browsed it

一把情况下模拟点击一般两个方面,模拟点击超级连接事件
firefox的兼容的函数为
对HTMLAnchorElement 加入onclick事件

复制代码代码如下:

try {
// create a element so that HTMLAnchorElement is accessible
document.createElement('a');
HTMLElement.prototype.click = function () {
if (typeof this.onclick == 'function') {
if (this.onclick({type: 'click'}) && this.href)
window.open(this.href, this.target? this.target : '_self');
}
else if (this.href)
window.open(this.href, this.target? this.target : '_self');
};
}
catch (e) {
// alert('click method for HTMLAnchorElement couldn\'t be added');
}

下面是具体的应用

[Ctrl+A 全选 注: 如需引入外部Js需刷新才能执行]

如果是普通的html添加点击
这一段使得FireFox的HTMLElement具有click方法(add click method to HTMLElement in Mozilla)
复制代码代码如下:

try {
// create span element so that HTMLElement is accessible
document.createElement('span');
HTMLElement.prototype.click = function () {
if (typeof this.onclick == 'function')
this.onclick({type: 'click'});
};
}
catch (e) {
// alert('click method for HTMLElement couldn\'t be added');
}

下面是网友的其它相关文章也可以参考下。
最近做东西发现用户在网页输入框里面按回车的行为是不固定的。。。
特别是在网页有多个表单的时候
于是搜了一把找了一个模拟点击的js,经测试能在firefox和ie上运行
复制代码代码如下:

function doClick(linkId, e){
if(e.keyCode != 13){
return;
}
var fireOnThis = document.getElementById(linkId)
if (document.createEvent)
{
var evObj = document.createEvent('MouseEvents')
evObj.initEvent( 'click', true, false )
fireOnThis.dispatchEvent(evObj)
}
else if (document.createEventObject)
{
fireOnThis.fireEvent('onclick')
}
}

其中e是event,内置对象,linkId是模拟被点击的对象id
比如
这样的话就能让用户按回车来提交表单了~
opera可以再改一下
复制代码代码如下:

Javascript 模拟点击事件(点击链接与html点击) 兼容IE/Firefox_javascript技巧
click me


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!