简体   繁体   中英

Blazor get div position / coordinates

I'm creating a popup component and I want this to be movable. I can move it using the top / left style, but for now they are init to top:0;left:0; and so the popup appear on the top left corner of the page. I'm looking to make it appear on the center of the page and then get the Top Left coordinates of my div in ordor to manage properly my calcul after.

here is what I have now:

<div class="child-window" draggable="true" style="position:absolute; top: @(offsetY)px; left: @(offsetX)px; border-color: black;" @ondragend="OnDragEnd" @ondragstart="OnDragStart">
   <div class="cw-content">
      @Content
   </div>
</div>

@code {
   private double startX, startY, offsetX, offsetY;

   protected override void OnInitialized() {
        base.OnInitialized();
        ResetStartPosition();
    }

   private void ResetStartPosition() {
        //Set offsetX & offsetY to the top left div position
    }

   private void OnDragStart(DragEventArgs args) {
        startX = args.ClientX;
        startY = args.ClientY;
    }

    private void OnDragEnd(DragEventArgs args) {
        offsetX += args.ClientX - startX;
        offsetY += args.ClientY - startY;
    }
}

At the moment it is possible with JS only

public class BoundingClientRect
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Width { get; set; }
    public double Height { get; set; }
    public double Top { get; set; }
    public double Right { get; set; }
    public double Bottom { get; set; }
    public double Left { get; set; }
}

private async Task OnElementClick(MouseEventArgs e)
{
    var result = await JSRuntime.InvokeAsync<BoundingClientRect>("MyDOMGetBoundingClientRect", MyElementReference);

    var x = (int) (e.ClientX - result.Left);
    var y = (int) (e.ClientY - result.Top);
   
   // now you can work with the position relative to the element.
}

and

<script> MyDOMGetBoundingClientRect = (element, parm) => { return element.getBoundingClientRect(); }; </script>

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