event.preventDefaule() 该方法的作用是阻止默认的事件行为
<form action="1.html">
用户名:<input type="text" id="uname" />
<input type="submit" value="提交" id="sub"/>
</form>
<script>
$("#sub").click(function(event){
var uname = $("#uname").val();
if(uname==""){
alert("请填写用户名");
event.preventDefault();
}
});
</script>
获取鼠标位置
<style>
.box{background-color: #fff;width: 500px;height: 500px;position: absolute;top: 500px;left: 500px;}
#div{width: 300px;height: 300px;margin: auto;background-color:yellow;position: relative;top: 50px;}
.dot{position: absolute;top: 80%;left: 80%;width: 10px;height: 10px;border-radius: 10px;background-color: green;}
</style>
<body style="background: gray;">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<div class="box" >
<div id="div">
<div class="dot"></div>
</div>
</div>
<div style="height: 3000px;width: 2000px;"></div>
</body>
<script>
var btn = document.getElementById("div")
btn.onclick=function(event){
// 元素左上角
console.log('offsetX : ' + event.offsetX);
console.log('offsetY : ' + event.offsetY);
//浏览器左上角
console.log('clientX : ' + event.clientX)
console.log('clientY : ' + event.clientY)
//页面左上角
console.log('pageX : ' + event.pageX)
console.log('pageY : ' + event.pageY)
//屏幕左上角
console.log('screenX : ' + event.screenX)
console.log('screenY : ' +event.screenY)
}
</script>
.witch
<html>
<head>
<meta charset="utf-8">
<title>W3Cschool在线教程(w3cschool.cn)</title>
</head>
<body>
<p>在输入框中输入键盘上的字符获取按下字母的 Unicode 字符代码。</p>
<input type="text" size="40" onkeypress="myFunction(event)">
<p id="demo"></p>
<p><strong>注意:</strong> IE8 及更早版本不支持该属性。</p>
<script>
function myFunction(event) {
var x = event.which;
document.getElementById("demo").innerHTML = " Unicode 值为:" + x;
}
</script>
</body>
</html>
鼠标左键,中键,右键判断
<html>
<head>
<script type="text/javascript">
function whichButton(event)
{
var btnNum = event.button;
if (btnNum==2)
{
alert("您点击了鼠标右键!")
}
else if(btnNum==0)
{
alert("您点击了鼠标左键!")
}
else if(btnNum==1)
{
alert("您点击了鼠标中键!");
}
else
{
alert("您点击了" + btnNum+ "号键,我不能确定它的名称。");
}
}
</script>
</head>
<body onmousedown="whichButton(event)">
<p>请在文档中点击鼠标。一个消息框会提示出您点击了哪个鼠标按键。</p>
</body>
</html>