最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I have an element follow the mouse without jQuery - Stack Overflow

programmeradmin2浏览0评论

I have this but it doesn't work

var box = document.getElementById("box");

window.addEventListener('mousemove', function(e){
    var left = e.pageX;
    box.style.left = left;
});

If I just replace box.style.left = left; with jQuery it works fine

$('#wrap').css ({   
    left: left  
});

but I'm just so confused... Why is box.style.left = left; not working when it's practically the same thing?

I have this but it doesn't work

var box = document.getElementById("box");

window.addEventListener('mousemove', function(e){
    var left = e.pageX;
    box.style.left = left;
});

If I just replace box.style.left = left; with jQuery it works fine

$('#wrap').css ({   
    left: left  
});

but I'm just so confused... Why is box.style.left = left; not working when it's practically the same thing?

Share Improve this question asked Aug 16, 2017 at 6:56 Magdi GamalMagdi Gamal 6781 gold badge12 silver badges28 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

The CSS left property requires units. You're not giving it any. jQuery's css adds "px" for you when you give it a number, which is why the jQuery one works.

Add a "px":

box.style.left = e.pageX + "px";

You also have to give top value

Hope this snippet will help

    var box = document.getElementById("box");

window.addEventListener('mousemove', function(e){
    var left = e.pageX+"px";
    box.style.left = left;
});
.moveAble {
    position: absolute;
}
<div id="box" class="moveAble">
AAAA
</div>

发布评论

评论列表(0)

  1. 暂无评论