您好,欢迎访问一九零五行业门户网

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

一把情况下模拟点击一般两个方面,模拟点击超级连接事件
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可以再改一下
复制代码 代码如下:
click me
其它类似信息

推荐信息