window.onload=function(){
var op = document.getElementById('p');
var timer= null;
op.onmouseover=function(){
startMove1();
}
op.onmouseout=function(){
startMove2();
}
function startMove1(){
clearInterval(timer);
timer=setInterval(function(){
if(op.offsetLeft==0){
clearInterval(timer);
}else{
console.log(111);
op.style.left=op.offsetLeft+10+'px';
}
},30);
}
function startMove2(){
clearInterval(timer);
timer=setInterval(function(){
if(op.offsetLeft==-150){
clearInterval(timer);
}else{
op.style.left=op.offsetLeft-10+'px';
}
},30);
}
}
<p id="p">
<p id="p1">分享到</p>
</p>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
问题1:
问题2:
问题3;
谁说onmouseout没有执行呢???你可以在事件中加一个console.log打印看看,分别是执行的很好。我想你的问题是为什么op就不动呢?
是啊,它为什么就不动呢?明明有设置它的位置的op.style.left=op.offsetLeft-10+'px';
这要涉及到CSS的问题,因为当前op的的定位方式是“流模式”,它的定位同浏览器实时计算所得,JS代码无法更改它的位置。如果你想要看看效果,可以把定位方式设置为position:absolute即可。刷新页面可以看到你的p在跳来跳去。
首先,你的onmouseout的确是执行了的,只是你的style在js控制后你没有看到效果


根据的你代码我脑补你是要让你的p移动对吧,如果你要让css的left生效的话就一定要给这个元素添加
position
属性才能让left
有效: