当前位置: 首页 > 图文教程 > 网络编程 > Javascript > Javascript 模拟点击事件(点击链接与html点击) 兼容IE/Firefox

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 817 ::
收藏到网摘: n/a

Javascript 模拟点击事件,一般情况下ie支持的,firefox并不支持。所以可以通过下面的方法解决。

一把情况下模拟点击一般两个方面,模拟点击超级连接事件
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 全选 提示:你可先修改部分代码,再按运行]

如果是普通的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
比如<INPUT id="test" onkeypress="doClick("buttonId", event)">
这样的话就能让用户按回车来提交表单了~
opera可以再改一下
复制代码 代码如下:

<img id="a" src="/a.jpg" onclick="alert('a');"/><div onclick="clickObj('a')">click me</div>
<script language="javascript">
<!--
function clickObj(o){
var o = document.getElementById(o);
if( document.all && typeof( document.all ) == "object" ) //IE
{
o.fireEvent("onclick");
}
else
{
var e = document.createEvent('MouseEvent');
e.initEvent('click',false,false);
o.dispatchEvent(e);
}
}
//-->
</script>