js阻止默认浏览器行为与冒泡行为的实现代码


Posted in Javascript onMay 15, 2016

在前端开发工作中,由于浏览器兼容性等问题,我们会经常用到“停止事件冒泡”和“阻止浏览器默认行为”。

1. 阻止浏览器的默认行为

function stopDefault(e) { 
//如果提供了事件对象,则这是一个非IE浏览器 
if(e && e.preventDefault) { 
//阻止默认浏览器动作(W3C) 

e.preventDefault(); 
} else { 

//IE中阻止函数器默认动作的方式 

window.event.returnValue = false; 
} 
return false; 
}

2. 停止事件冒泡

function stopBubble(e) { 
//如果提供了事件对象,则这是一个非IE浏览器 
if(e && e.stopPropagation) { 
//因此它支持W3C的stopPropagation()方法 

e.stopPropagation(); 
} else { 

//否则,我们需要使用IE的方式来取消事件冒泡 

window.event.cancelBubble = true; 
} 
return false; 
}

具体应用实例:写好的一个项目,今天交给用户使用,返回了一大堆问题,其中有一个很精典:

一个页面,有一个表单,用来提交表单的按钮是个button,用jquery来响应这个按钮的点击动作,通过post提交,供用户输入的是一个文本框,用户输入完要填的东西之后,直接按回车键,就相当于按了那个button,刚开始没注意这个问题,一按回车,就跳转到了另外一个页面,查了很多资料,才发现要阻止浏览器的默认行为,,因为SUBMIT的默认行为是提交表单,那么你的JS就不会执行了。所以先取消默认行为。然后执行你的JQ来提交。具体的我也说不清楚,只知道若文本框的type="submit",直接点击按钮的时候就会跳到另外一个页面,若type="button",则点击按钮的时候不会出现这样的情况,可按回车键的时候会跳到另外一个页面,解决方法,看下面代码:

<input type="text" name="appGrpName_s" id="appGrpName_s" onkeydown="enter_down(this.form, event);"/>

<script type="text/javascript"> 
function enter_down(form, event) { 
if(event.keyCode== "13") { 
stopDefault(event); 
submitForm(form,'actionDiv'); 
} 
} 
function stopDefault(e) { 
//如果提供了事件对象,则这是一个非IE浏览器 
if(e && e.preventDefault) { 
//阻止默认浏览器动作(W3C) 

e.preventDefault(); 
} else { 

//IE中阻止函数器默认动作的方式 

window.event.returnValue = false; 
} 
return false; 
} 
</script>

通过上面的代码就可以实现按回车的时候相当于点击“提交”按钮。且上面的代码兼容IE、FF浏览器。

有时候遇到需要屏蔽浏览器的一些快捷键行为时,比如说:ff下按Backspace键,会跳到上一个浏览器的历史记录页面;

注意要在onkeydown事件中调用stopDefault(event)函数,在onkeyup事件中调用是不成功的。

<span style="color: rgb(51, 153, 51);"><</span>a onclick<span style="color: rgb(51, 153, 51);">=</span><span style="color: rgb(51, 102, 204);">"toggleFriendFuncList(event, '6708062', 'he');"</span><span style="color: rgb(51, 153, 51);">></</span>a<span style="color: rgb(51, 153, 51);">></span>

由于href是空值,如果不阻止浏览器的默认行为,产生的效果就是刷新页面。

现在我们需要做的就是阻止href的链接事件,而去执行onclick事件。

老的处理方式:

<span style="color: rgb(51, 153, 51);"><</span>a onclick<span style="color: rgb(51, 153, 51);">=</span><span style="color: rgb(51, 102, 204);">"toggleFriendFuncList(event, '6708062', 'he');"</span> href<span style="color: rgb(51, 153, 51);">=</span><span style="color: rgb(51, 102, 204);">"javascript:void(0);"</span><span style="color: rgb(51, 153, 51);">></</span>a<span style="color: rgb(51, 153, 51);">></span>

jquery的写法:

1)return false :In event handler ,prevents default behavior and event bubbing 。
return false 在事件的处理中,可以阻止默认事件和冒泡事件。

2)event.preventDefault():In event handler ,prevent default event (allows bubbling) 。
event.preventDefault()在事件的处理中,可以阻止默认事件但是允许冒泡事件的发生。

3)event.stopPropagation():In event handler ,prevent bubbling (allows default behavior).
event.stopPropagation()在事件的处理中,可以阻止冒泡但是允许默认事件的发生

prototype的写法:

Event.stop(event)
用法介绍:
事件发生后,浏览器通常首先触发事件发生元素上的事件处理程序,然后是它的父元素,父元素的父元素……依此类推,直到文档的根元素为止。这被称为 事件冒泡,是事件传播的最常见的方式。当处理好一个事件后,你可能想要停止事件的传播,不希望它继续冒泡。
当你的程序有机会处理事件时,如果这个事件具有 默认行为,同时浏览器也会处理它。例如,点击导航链接、将表单提交到服务器、在一个单行文本框中按下回车键等等。如果对这些事件你定义了自己的处理方式,可能会非常希望阻止相关的默认行为。

但是,有时候还是不能解决相应的问题,明明已经调用了阻止浏览器默认行为的方法,可在按回车的时候还是会调用默认行为,最终也没有找到问题所在,只好把回车键禁用了,实际上是用Tab键代替回车键。代码如下:

<script language="javascript" event="onkeydown" for="document"> 
//若为回车键 
if ( event.keyCode == 13 ) { 
//改成Tab键,这样每次按回车都起到了Tab的功效,光标跳到下一个对象 
event.keyCode = 9; 
} 
</script> 
<script language="javascript" type="text/javascript"> 
//禁用Enter键表单自动提交 
document.onkeydown = function(event) { 
var target, code, tag; 
if (!event) { 
event = window.event; //针对ie浏览器 
target = event.srcElement; 
code = event.keyCode; 
if (code == 13) { 
tag = target.tagName; 
if (tag == "TEXTAREA") { return true; } 
else { return false; } 
} 
} 
else { 
target = event.target; //针对遵循w3c标准的浏览器,如Firefox 
code = event.keyCode; 
if (code == 13) { 
tag = target.tagName; 
if (tag == "INPUT") { return false; } 
else { return true; } 
} 
} 
}; 
</script>

具体用法试例:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<%@ include file="/pages/common/global.jsp"%> 
<html> 
<head> 
<title>三水点靠木</title> 
<meta http-equiv="pragma" content="no-cache"> 
<meta http-equiv="cache-control" content="no-cache"> 
<meta http-equiv="expires" content="0"> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
<script> 
function gotoPage(currentPage,form) { 
goto_Page(currentPage,form,"actionDiv"); 
} 
function addAppGrp(){ 
$("#actionDiv").load("${contextPath }/pages/manage/business/add.jsp"); 
$("#chance_search_div").hide(); 
} 
function modifyAppGrp(idName){ 
var id=encodeURIComponent(idName); 
var url = contextName + "/appGrpAction.do?method=addAppGrp&appGrpName="+id; 
retrieveURL(url,'actionDiv'); 
$("#chance_search_div").hide(); 
} 
function savebusiness(thisForm){ 
var name = $("#appGrpName").val(); 
if(name.trim()==""){ 
alert("分组名称不能为空。"); 
return; 
} 
submitForm(thisForm,null,afterSave); 
return ; 
} 
function afterSave(content){ 
if(content!=null&&content!=""){ 
var arr = content.split(","); 
if(arr[0]=="true"){ 
$("#chance_search_div").show(); 
//当前结点 
var itemId = "0::" + $("#appGrpName").val(); 
//父结点,因为只有添加根应用分组时才会执行这个方法,所以父结点统一为-1 
var parentId = -1; 
//当前结点显示名称 
var itemText = $("#appGrpName").val(); 
//添加新结点 
tree.insertNewChild(parentId, itemId, itemText, doOnClick, 'myfolderClosed.gif' ,'myfolderOpen.gif','myfolderClosed.gif'); 
retrieveURL("${contextPath}/appGrpAction.do?method=appGrpList","actionDiv"); 
return; 
} 
alert(arr[1]); 
return; 
} 
alert("保存失败"); 
return; 
} 
function deleteBusiness(thisForm,idName){ 
if(confirm("确认要删除么?")){ 
var id=encodeURIComponent(idName); 
retrieveURL("${contextPath}/appGrpAction.do?method=deleteAppGrp&appGrpName=" + id,null,null,function(content){ 
if(content!=null&&content!=""){ 
var arr = content.split(","); 
if(arr.length==3&&arr[2]=='y'){ 
var msg = "该应用组下有应用,要强制删除么?"; 
if(confirm(msg)){ 
retrieveURL("${contextPath}/appGrpAction.do?method=forceDelAppGrp&appGrpName="+id,null,null,afterForceDel); 
} 
return; 
} 
if(arr.length==2){ 
if(arr[0]=="true"){ 
//当前结点 
itemId = "0::" + idName; 
tree.deleteItem(itemId); 
retrieveURL("${contextPath}/appGrpAction.do?method=appGrpList","actionDiv"); 
return; 
} 
alert(arr[1]); 
} 
return; 
} 
alert("删除失败"); 
return; 
}); 
return ; 
} 
} 
function afterForceDel(){ 
if(content!=null&&content!=""){ 
var arr = content.split(","); 
if(arr[0]=="true"){ 
monitorTree(); 
retrieveURL("${contextPath}/appGrpAction.do?method=appGrpList","actionDiv"); 
return; 
} 
alert(arr[1]); 
return; 
} 
alert("保存失败"); 
return; 
} 
function enter_down(form, event) { 
if(event.keyCode== "13") { 
stopDefault(event); 
submitForm(form,'actionDiv'); 
} 
} 
function stopDefault(e) { 
//如果提供了事件对象,则这是一个非IE浏览器 
if(e && e.preventDefault) { 
//阻止默认浏览器动作(W3C) 

e.preventDefault(); 
} else { 

//IE中阻止函数器默认动作的方式 

window.event.returnValue = false; 
} 
return false; 
} 
</script> 
</head> 
<body> 
<table style="width: 100%; align: center;"> 
<tr> 
<td style="text-align:left;"> 
<div id="chance_search_div"> 
<html:form action="appGrpAction.do?method=appGrpList"> 
<table class="form_t"> 
<tr> 
<th class="tablelogo"> 查询 
<input type="hidden" name="hidden_s" value="1" /> 
</th> 
</tr> 
<tr> 
<td style="text-align: left; padding-left: 50px;"> 
<br /> 
名称 
<input type="text" name="appGrpName_s" id="appGrpName_s" 
onblur="javascript:isSpecialChar(this);" onkeydown="enter_down(this.form, event);"/> 
<input type="button" class="button4C" value="查 询" 
onclick="javascript:submitForm(this.form,'actionDiv');" /> 
<input type="button" value="添 加" class="button4C" onclick="javascript:addAppGrp();"/> 
<br /> 
</td> 
</tr> 
</table> 
</html:form> 
</div> 
<div id="actionDiv"></div> 
</td> 
</tr> 
</table> 
<script><!-- 
$("#actionDiv").load("${contextPath }/appGrpAction.do?method=appGrpList&random=" + Math.random()); 
--></script> 
</body> 
</html>

以上这篇js阻止默认浏览器行为与冒泡行为的实现代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
JavaScript 数组循环引起的思考
Jan 01 Javascript
ExtJS 设置级联菜单的默认值
Jun 13 Javascript
Ext JS添加子组件的误区探讨
Jun 28 Javascript
javascript获取四位数字或者字母的随机数
Jan 09 Javascript
在for循环中length值是否需要缓存
Jul 27 Javascript
如何让一个json文件显示在表格里【实现代码】
May 09 Javascript
浅谈js的url解析函数封装
Jun 28 Javascript
jQuery实现带延时功能的水平多级菜单效果【附demo源码下载】
Sep 21 Javascript
JS简单实现滑动加载数据的方法示例
Oct 18 Javascript
Three.js基础学习教程
Nov 16 Javascript
JavaScript中变量提升与函数提升经典实例分析
Jul 26 Javascript
vue项目实现表单登录页保存账号和密码到cookie功能
Aug 31 Javascript
JQuery validate插件Remote用法大全
May 15 #Javascript
js阻止浏览器默认行为触发的通用方法(推荐)
May 15 #Javascript
Javascript自执行匿名函数(function() { })()的原理浅析
May 15 #Javascript
js阻止浏览器默认行为的简单实例
May 15 #Javascript
js添加绑定事件的方法
May 15 #Javascript
JavaScript绑定事件监听函数的通用方法
May 14 #Javascript
易被忽视的js事件问题总结
May 14 #Javascript
You might like
CI框架给视图添加动态数据
2014/12/01 PHP
Yii2使用dropdownlist实现地区三级联动功能的方法
2016/07/18 PHP
在浏览器窗口上添加遮罩层的方法
2012/11/12 Javascript
jQuery的attr与prop使用介绍
2013/10/10 Javascript
jquery实现的点击翻书效果代码
2015/11/04 Javascript
jQuery向webApi提交post json数据
2017/01/16 Javascript
温故知新——JavaScript中的字符串连接问题最全总结(推荐)
2017/08/21 Javascript
AngularJS遍历获取数组元素的方法示例
2017/11/11 Javascript
Vue-cli配置打包文件本地使用的教程图解
2018/08/02 Javascript
[02:08:58]2014 DOTA2国际邀请赛中国区预选赛 Ne VS CIS
2014/05/22 DOTA
Python urls.py的三种配置写法实例详解
2017/04/28 Python
Python实现两款计算器功能示例
2017/12/19 Python
hmac模块生成加入了密钥的消息摘要详解
2018/01/11 Python
Python中sort和sorted函数代码解析
2018/01/25 Python
Python及Django框架生成二维码的方法分析
2018/01/31 Python
python实现淘宝秒杀聚划算抢购自动提醒源码
2020/06/23 Python
Python 爬虫之Beautiful Soup模块使用指南
2018/07/05 Python
详解windows python3.7安装numpy问题的解决方法
2018/08/13 Python
详解Python爬取并下载《电影天堂》3千多部电影
2019/04/26 Python
python opencv minAreaRect 生成最小外接矩形的方法
2019/07/01 Python
用Python画一个LinkinPark的logo代码实例
2019/09/10 Python
numpy np.newaxis 的实用分享
2019/11/30 Python
python中的itertools的使用详解
2020/01/13 Python
python调用API接口实现登陆短信验证
2020/05/10 Python
详解python datetime模块
2020/08/17 Python
HTML5使用DOM进行自定义控制示例代码
2013/06/08 HTML / CSS
互动出版网:专业书籍
2017/03/21 全球购物
美国女性卫生用品公司:Thinx
2017/06/30 全球购物
Servlet面试题库
2015/07/18 面试题
自荐信怎么写好
2013/11/11 职场文书
业绩倒数第一的检讨书
2014/09/24 职场文书
学习作风建设心得体会
2014/10/22 职场文书
组织生活会发言材料
2014/12/15 职场文书
nginx配置proxy_pass中url末尾带/与不带/的区别详解
2021/03/31 Servers
Pycharm连接远程服务器并远程调试的全过程
2021/06/24 Python
Go语言 详解net的tcp服务
2022/04/14 Golang