阻止默认行为
实现自定义的右键菜单,鼠标按下
按下的右键 往右键这个位置显示菜单
如果按下是别的键,菜单消失
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{margin: 0px;padding: 0px;}
#menu{width: 100px;height: 100px;background-color: grey;display: none;position: absolute;}
</style>
<script>
window.onload = function(){
//官方的右键菜单
document.oncontextmenu = function(){
return false;
}
var oMenu = document.getElementById("menu");
document.onmousedown = function(ev){
var e = ev || window.event;
if(e.button == 2){
oMenu.style.display = 'block';
oMenu.style.left = e.clientX + 'px';
oMenu.style.top = e.clientY + 'px';
}else{
oMenu.style.display = 'none';
}
}
}
</script>
</head>
<body>
<div id = 'menu'>
<ul>
<li>菜单1</li>
<li>菜单2</li>
<li>菜单3</li>
</ul>
</div>
</body>
</html>
效果:鼠标右键按在哪里,哪里出现
阻止超链接
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.onload = function(){
var a1 = document.getElementById("a1");
a1.onclick = function(){
return false;
}
}
</script>
</head>
<body>
<a id="a1" href="https://www.baidu.com">百度</a>
</body>
</html>
这种弄是简陋的阻止a链接默认行为的方式
缺点:运行到了return,后续的内容我们就执行不到了
下面介绍规范的方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.onload = function(){
var a1 = document.getElementById("a1");
a1.onclick = function(ev){
var e = ev || window.event;
preDef(e);
alert("后续的操作");
}
//编写一个跨浏览器阻止超链接默认行为的函数‘
function preDef(e){
if(e.preventDefault){
e.preventDefault();
}else{
window.event.returnValue = false;
}
}
}
</script>
</head>
<body>
<a id="a1" href="https://www.baidu.com">百度</a>
</body>
</html>