版权声明:转载请附上原文链接,谢谢;侵删。 https://blog.youkuaiyun.com/u014291497/article/details/52267604 </div>
<div id="content_views" class="markdown_views">
<!-- flowchart 箭头图标 勿删 -->
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path></svg>
<p>大多数情况下我们使用左键来进行页面交互,而右键大部分对于开发者来说是审查元素的,有的时候我们也要自定义鼠标右键点击行为来达到更好的交互性,常见的有漫画左键前进、右键后退。</p>
第一步我们要屏蔽浏览器默认的右键点击行为,即阻止弹出框。
首先要将阻止弹出函数绑定到目标元素上:
//阻止浏览器默认右键点击事件
$("div").bind("contextmenu", function(){
return false;
})
- 1
- 2
- 3
- 4
如此一来,div元素的右击事件就被屏蔽了,而浏览器其他区域不受影响,如果你想在整个页面屏蔽右击事件,只需这样做:
document.oncontextmenu = function() {
return false;
}
- 1
- 2
- 3
接下来就可以为元素绑定右击响应函数了:
$("div").mousedown(function(e) {
console.log(e.which);
//右键为3
if (3 == e.which) {
$(this).css({
"font-size": "-=2px"
});
} else if (1 == e.which) {
//左键为1
$(this).css({
"font-size": "+=3px"
});
}
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
示例效果为右击字体缩小,左击字体变大,且其它区域可以响应默认右击事件。
完整代码:
<head>
<style type="text/css">
div{
font-size:20px;
}
</style>
<script src="../jquery.js"></script>
<script>
$(function() {
//阻止浏览器默认右键点击事件
/*document.oncontextmenu = function() {
return false;
}*/
//某元素组织右键点击事件
$("div").bind("contextmenu", function(){
return false;
})
$("div").mousedown(function(e) {
console.log(e.which);
//右键为3
if (3 == e.which) {
$(this).css({
"font-size": "-=2px"
});
} else if (1 == e.which) {
//左键为1
$(this).css({
"font-size": "+=3px"
});
}
})
})
</script>
</head>
<body>
<div>
div
</div>
</body>
此文档的作者:justforuse
Github Pages:justforuse