ITeye博客

简单自定义鼠标右击事件

QuarterLifeForJava · 2014-07-25 20:16 · 前端开发 · Web前端 · Markdown


<html>
<head>
<script>
var x;
var y;
var flag = true;

function test(){
	//绑定鼠标右击事件
	document.getElementById("a").oncontextmenu = function() {
		if(!flag){
			var createDiv = document.getElementById("b");
			//移除div
			createDiv.outerHTML = "";
		}

		var oDiv=document.createElement('div');
        oDiv.style.left=x; 
        oDiv.style.top=y-50;  
        oDiv.style.border='1px solid #FF0000';
        oDiv.style.position='absolute'; 
        oDiv.style.width='50px'; 
        oDiv.style.height='50px';
		oDiv.style.background="blue";
		oDiv.id='b'; 
        document.body.appendChild(oDiv);

		flag = false;

		return false;
	}

	//得到鼠标的位置
	document.onmousemove=function(e){
		e = e ? e: window.event;
		x = e.screenX;
		y = e.screenY;
	}
	/**
    //获取绝对位置:
	var ex1 = $("#a").offset().top;
	var ey1 = $("#a").offset().left;
	console.log(ex1);
    console.log(ey1);
    
    //获取相对(父元素)位置: 
    var ex2 = $("#a").position.top;
    var ey2 = $("#a").position().left;
    console.log(ex2);
    console.log(ey2);
    */

}
</script>
</head>
<!-- oncontextmenu="return false" -->
<body onload="test()">
<div id="a" style="width:100px;height:100px;background-color:red"></div>
</body>
</html>

评论(1)

  1. #1 楼 · 猿哥 · 2014-08-15 16:58

    :?:

评论功能维护中,当前仅展示历史评论。