简体   繁体   中英

How to move element's x/y position with js?

在此处输入图片说明 I have added a picture to describe what I need. here I have a container with yellow border and content with a red border, I want it to scroll to left for 1 container's width when I click the button in the container.

I have tried the CSS animation but it seems not what I want. so it's there a way to achieve what I want?

I have write a demo here : https://codesandbox.io/s/keen-panini-hel36

Start by adding a class to the div you'll want to move (moveDiv) and style it with position:relative .

Then, add a class to the button you want to click to trigger the action (actionButton).

Afterwards, place the following JavaScript in the end of the page in between tags

document.getElementsByClassName("actionButton").addEventListener('mousedown',function(){
    var left = document.getElementsByClassName("moveDiv")[0].style.left;
    left = left === '150px' ? 0 : '150px';
    document.getElementsByClassName("moveDiv")[0].style.left = left;
});

This has an event listener knowing when the mouse is down (when user clicks the button). Change the left position accordingly to suit your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM