gpt4 book ai didi

javascript - 使用和不使用事件处理程序时 javascript 中事件的不同行为

转载 作者:行者123 更新时间:2023-11-30 05:38:19 25 4
gpt4 key购买 nike

我正在练习 HTML5 和 javascript:我创建了一个随着用户鼠标移动而移动的小方 block 。

不过,根据我收听事件的方式不同,广场的 react 也不同。

第一个版本的代码在标签中使用了“onMouseMove”和“onClick”。(我试着把它放在 fiddle 上,但没有用..)-->

<html>
<head>
<style>
#carre_rouge
{
background-color: red;
position: absolute;
height:40px;
width:60px;
top:50px;
left:50px;
}
</style>

</head>
<body onmousemove="souris(event)" onclick="clique(event)">
<div id="carre_rouge">CARRE ROUGE</div>
<div id="carreX"></div>


</body>
</html> //ip adresses gateway, put numbers

<script>

var nomore =false;

function souris(event){
if(!nomore){
document.getElementById("carre_rouge").style.top=event.clientY-10;
document.getElementById("carre_rouge").style.left=event.clientX;
}
}


function clique(event)
{

nomore=true;
document.getElementById("carre_rouge").style.top=event.clientY-10;
document.getElementById("carre_rouge").style.left=event.clientX;

}



</script>

==>这个上面的版本工作得很好,但是在 body 标签中使用了“onmousemove”和 onclick,这很麻烦..

其他版本使用函数 addEvent() 来控制事件。

<html>
<head>
<style>
#carre_rouge
{
background-color: red;
position: absolute;
height:40px;
width:60px;
top:50px;
left:50px;
}
</style>

</head>
<body>
<div id="carre_rouge">CARRE ROUGE</div>
<div id="carreX"></div>
<script>


</script>

</body>
</html> //ip adresses gateway, put numbers

<script>
function addEvent(obj,event,fct)
{
if(obj.attachEvent)
obj.attachEvent('on' + event,fct);
else
obj.addEventListener(event,fct,true);
}


var nomore =false;

function souris(event){
if(!nomore){
document.getElementById("carre_rouge").style.top=event.clientY-10;
document.getElementById("carre_rouge").style.left=event.clientX;
}
}


function clique(event)
{

nomore=true;
document.getElementById("carre_rouge").style.top=event.clientY-10;
document.getElementById("carre_rouge").style.left=event.clientX;

}

addEvent(document.getElementById("carre_rouge"),"mousemove",souris);
addEvent(document.getElementById("carre_rouge"),"click",clique);


</script>

这个版本只能把正方形“推”到右边???

我真的不明白为什么,代码非常相似。

你能教教我吗?

拉斐尔

最佳答案

这仅仅是因为在第一个示例中,您的 mousemove 事件绑定(bind)在主体上,而在第二个示例中,它绑定(bind)在元素本身上。

现在,当您在第一个示例中移动鼠标时,您始终在 body 上。但在第二个示例中,由于您在光标上向右移动,因此当您将鼠标光标移至左侧时,您不再位于 div 上。您的事件不会触发。但是,当您向右移动时,您的鼠标会在 div 上移动,因为它位于光标的右侧。

只需在 document.body 或仅 document 上绑定(bind)事件。就像你的第一个例子。

addEvent(document.body,"mousemove",souris);
addEvent(document.body,"click",clique);
//or
addEvent(document,"mousemove",souris);
addEvent(document,"click",clique);

关于javascript - 使用和不使用事件处理程序时 javascript 中事件的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22251677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com