简体   繁体   中英

How to get marginLeft from an element with absolute position?

I'm trying to add an information box over something when you hover over it with your mouse, but I need to get the element's left margin since it moves, but it doesn't have a margin-left property in CSS, and it's position is relative so I don't really need to add a margin-left property. I tried doing element1.style.marginLeft = element2.style.marginLeft but it always returns 0

Here is an example which uses only CSS to show a popover info box. It uses transform to move the box around instead of margin . The reason is that animating with transform is more performant than margin and the animation will appear much smoother on all devices. The following example also uses some WAI-ARIA attributes to make it more accessible for screen reader users.

 .container { position: relative; display: inline-block; } [role=dialog] { position: absolute; opacity: 0; top: 50%; left: 50%; transform: translate(-50%, calc(-50% + 45px)); transition: 0.3s transform, 0.3s opacity; background-color: #333; color: white; font-family: sans-serif; padding: .5em; width: 70%; pointer-events: none; font-size: .9rem; } .myInfo:hover+[role=dialog], .myInfo:focus+[role=dialog] { opacity: 1; transform: translate(-50%, calc(-50% + 40px)); } p { margin: 0; padding: 1em 2em 1em 1em; background-color: #eee; position: relative; } p img { position: absolute; top: 50%; right: 10px; transform: translateY(-50%); }
 <div class="container"> <p class="myInfo" aria-describedby="infoDialog">I have more information <img src="https://image.flaticon.com/icons/svg/1828/1828885.svg" alt="Info icon" width="16" height="16" role="presentation"></p> <div id="infoDialog" role="dialog"> More information found here </div> </div>

jsFiddle

我所做的只是没有让它们以某种方式分开,我所做的只是将两个元素都设置在<div>元素中,它最终起作用了!

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