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

I have this but it doesn't workvar box = document.getElementById("box");window.addEventL

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745450297a4628236.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信