2

我的页面中有这段代码

<body onmouseup="fun()">
.......
.......
<button id="ele">Exclude</button>

</body>

我怎样才能实现这样的目标

function fun()
{
    if(MOUSE RELEASE IS ON TOP OF BUTTON #ele)
    {
        console.log('Mouse released on top of the button');
    }
    else
    {
        console.log('Mouse released');
    }
}
4

3 回答 3

3

如果您使用的是 jQuery,我建议您使用.on()来绑定事件。您可以使用该event.target元素来查看它是否是按钮。

$(document).ready(function(){
    $('body').on('mouseup', fun);
    function fun(event){
        if($(event.target).is('#ele')){
             console.log('Mouse released on top of the button');
        }else{
            console.log('Mouse released');
        }
    }
});
于 2013-01-04T04:13:51.313 回答
1

使用event.stopPropagation,像这样:

html

<button id="ele">Exclude</button>
<br>
<br>
<div>fun</div>

js

document.body.onmouseup = function(){ fun(); };
function fun(){
 console.log("fun");   
}
var el = document.getElementById("ele");
el.onmouseup = function(e){ e.stopPropagation(); };

演示:http: //jsfiddle.net/GgKsQ/

这是一个使用 jQuery 的演示:http mouseup: //jsfiddle.net/GgKsQ/1/

于 2013-01-04T04:27:05.297 回答
1

这是一个正统的代码,它为您提供所需的内容。请复制到您的编辑器中并检查。

<!DOCTYPE html>
<html>
<body onmouseup="fun()">
The content of the body element is displayed in your browser.
<br/><br/><br/><br/><br/><br/><br/><br/>
<div id="Exclude" onmousedown="fun2()"> Exclude Me Please </div>
</body>
<script>
var idPressed = 0;
function fun() {
if (idPressed == 0)
console.log('Mouse released');
idPressed = 0;
//alert("Whatever "+this.id);
}

function fun2() {
idPressed = 1;
console.log('Mouse released 2');
//alert("Whatever 2"+this.id);
}

</script>
</html>
于 2013-01-04T04:28:15.610 回答