admin管理员组

文章数量:1426023

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>

本文标签: javascriptHow do I have an element follow the mouse without jQueryStack Overflow