逃走的按钮-javascript

一、 由来

    曾有一些“纯属娱乐”的网页,有一些有奖问答题,但又故意让你点不到正确的答案:当你鼠标

一靠近按钮,按钮就逃开了。自己也试着做了一个,供大家学习娱乐。

 

二、 原理

    其实非常简单:当鼠标放到按钮上面时,改变按钮的位置(赋随机值)。

 

三、 代码

 

代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    
<head>
        
<title>你中奖了!!!!</title>
    
<style>
        body 
{
            text-align
:center;
        
}
        #d 
{
            margin-left
:0 auto;
            margin-right
:0 auto;
            text-align
:center;
        
}
        input 
{
            width
:100px;
            height
:40px;
        
}
    
</style>
    
    
</head>
    
<body>
        
<div id="d">
            
<h2>恭喜你得了一等奖,点击领取:</h2>
            
<input type="button" onmouseover="move(this);" onclick="alert('骗你的=_=');" value="确定" />
        
</div>
    
</body>
    
<script type="text/javascript" >
        
var height = document.documentElement.clientHeight - 100;    //按钮可能上下移动的距离
        var width = document.documentElement.clientWidth - 40;        //按钮可能左右移动的距离
        function move(obj) {
            obj.style.position 
= "absolute";
            obj.style.top 
= Math.random() * height + "px";
            obj.style.left 
= Math.random() * width + "px";
        }
        
function cancel() {
            alert(
"你已放弃领奖,谢谢!");
            window.close();
        }
    
</script>
</html>

 

 

四、 注意

  (1) style下的属性在被赋值之前为空。

  (2) 记得要在style.top/left等之后加上px,否则对于许多浏览器都不能正确设置该

值。

posted @ 2009-12-07 08:17  小冰  阅读(323)  评论(0编辑  收藏  举报