西装外套。如何在onmousemove事件中捕获鼠标?

How to capture mouse in onmousemove event in Blazor like UIElement.CaptureMouse() in WPF?

评论
  • 切克闹
    切克闹 回复

    这是一个小示例,展示了如何在显示ClientX值的同时将鼠标移至div上:

     <div style="background-color:aliceblue" @onmousemove="@((args) => 
      mousemove=args.ClientX.ToString())"> Move the mouse over the div 
      element</div>
     <p>ClientX: @mousemove</p>
    
     @code{
        private string mousemove;
    
     }
    

    注意:@onmousemove指令的值是具有单个参数MouseEventArgs的lambda表达式。当鼠标移到div的表面上时,会不断触发mousemove事件,并且 将类型为MouseEventArgs的args参数传递给我们的方法,在将其转换为字符串值之后,将其分配给该方法,并将其分配给显示其值的变量...

    希望这可以帮助!

  • verror
    verror 回复

    ...在Blazor中就像UIElement.CaptureMouse()

    The closest match would be Element.setPointerCapture()

    In order to use it you will need to get an ElementReference in Blazor with @ref and a JS method to invoke setPointerCapture on it. You need to pass a pointerId that you get from PointerEventArgs.

    不要使用与Mouse *相关的​​事件/方法,它们在JS中或多或少不推荐使用。

    因此,您可以从以下内容开始:

     <div @ref="myTarget" @onpointerdown="StartCapture">  ... </div>
    
    @code{    
        ElementReference myTarget;
    
        async Task StartCapture(PointerEventArgs args)
        {
            await JSRuntime.InvokeVoidAsync("myJsFunctions.capturePointer",
                     myTarget, args.PointerId);
        }    
    }