国外的很多摄影或图片网站,为了防止别人随意保存图片,想出了很多办法。其中,最简单的要数把图片的url放到元素的背景中去,这样一来普通用户就无法右键另存为,实现和操作起来也简便。
有时候,鼠标右键所出现的内容,往往不是我们所想要的内容,更多的是浏览器为我们所设想的东西。所以,有些网站就是屏蔽了右键菜单。这样一来用户就找不到另存按钮,同时也无法简单的右键查看源码,但大大损失了鼠标右键的功能。所以,QQ邮箱和WEB QQ很早就做到了一点,那就是通过JS和CSS模拟出一个右键菜单,来帮助用户操作和引导用户去操作。
今天所说的内容,也可以说是在此基础上的一个衍化。
代码分为了3个部分,分别写成了插件形式方便调用:
1.屏蔽右键
2.右键出现版权提示信息(也可以是菜单)
3.灯箱效果(乍看有点陌生,但经常上视频网站的人肯定很熟悉,就是通常所说的开灯和关灯效果)
屏蔽右键菜单部分:
(function($) {
$.fn.ShieldingRight=function(){
$(document).bind('contextmenu',function(e){ //屏蔽右键菜单(jQuery方法)
return false;
});
// document.oncontextmenu=function(){return false;} //屏蔽右键菜单(原生js方法)
};
})(jQuery);
灯箱开关部分:
(function($) {
$.fn.LightSwitch=function(options){
var defaults = {
lightSwitch:"#switch",
lightBox:"#lightBox"
};
var options = $.extend(defaults, options);
$(options.lightSwitch).click(function(){ //点击图片区域
if ( $(options.lightSwitch).attr("class") == "active" ) {
$(this).removeClass("active");
$(options.lightBox).remove();
}else{
$(this).addClass("active");
$("body").append("<div id=\"lightBox\"></div>");
};
});
$(options.lightSwitch).mouseout(function(){ //增加一个判断,否则无法遍历到遮罩层
$(options.lightBox).click(function(){ //点击遮罩层
$(this).remove();
$(options.lightSwitch).removeClass("active");
});
});
};
})(jQuery);
提示信息部分:
(function($) {
$.fn.tightTips=function(options){
var defaults = {
tipArea:"#thephoto",
tipCon:"#copyright"
};
var options = $.extend(defaults, options);
$(options.tipArea).mousedown(function(e){ //鼠标点击图片区域
/* 坐标及大小计算 */
var offsetX=e.pageX,
offsetY=e.pageY,
copyrightW=$(options.tipCon).outerWidth(true),
windowW=$(window).width(),
thisW=$(this).outerWidth(true)+$(this).offset().left;
/* 判断鼠标事件 */
if(3 == e.which){ //1 = 鼠标左键 left; 2 = 鼠标中键; 3 = 鼠标右键
if ( offsetX+copyrightW > thisW ) {
$(options.tipCon).css({"left":"auto","right":windowW-offsetX,"top":offsetY});
$(options.tipCon).stop(true,false).animate({"opacity":"1"},500).delay(1500).animate({"opacity":"0"},500);
}else{
$(options.tipCon).css({"right":"auto","left":offsetX,"top":offsetY});
$(options.tipCon).stop(true,false).animate({"opacity":"1"},500).delay(1500).animate({"opacity":"0"},500);
}
}
});
};
})(jQuery);
调用方法:
<script type="text/javascript">
$(function(){
/* 屏蔽右键菜单 */
$.fn.ShieldingRight();
/* 灯箱开关 */
$.fn.tightTips({
tipArea:"#thephoto", //设置点击区域(如果要整个页面,那就用body)
tipCon:"#copyright" //提示内容
});
/* 提示信息 */
$.fn.LightSwitch({
lightSwitch:"#switch", //触发灯箱效果的元素
lightBox:"#lightBox" //遮罩层
});
/* 备注:上面的#代表CSS引用方式为id的情况,如果用class那这里的#就改成. 例:tipArea:".thephoto" */
});
</script>
测试环境:Opera 12、Firefox 17、Chrome 23、IE9+ (本文仅供学习交流作用,所以IE9以下版本未做兼容处理)
遮罩层兼容性问题,请参考:《Ublue jQuery 弹出框 始终垂直于屏幕中间 完美兼容IE6》中遮罩层写法。
功能说明:鼠标右键图片和左键单击图片
感谢您的阅读,本文由 蓝色梦想 版权所有。如若转载,请注明出处:蓝色梦想 - jQuery鼠标右键版权提示+灯箱效果