簡體   English   中英

Javascript 單擊事件在 Blazor 客戶端應用程序中不起作用

[英]Javascript click event not working in Blazor client side app

我是 Blazor 的新手,我創建了一個非常簡單的 Webassembly 應用程序。 當我點擊它時,我想要一個 href 鏈接轉到頁面下方的 div,但 Javascript 點擊事件不起作用。 在 Index.razor 頁面中, JsRuntime.InvokeVoidAsync("clicker")正在工作,並且在頁面加載時發生alert("In clicker") ,但是點擊/href 轉到“介紹”div 對愛或錢 :-/

索引.html

<!DOCTYPE html>
<html>
<head>
    <title>My Blazor App</title>
    <!--script type='text/javascript' src='./scripts/app.js'-->
</head>
<body>
    <app>Loading...</app>
    <script src="_framework/blazor.webassembly.js"></script>
    <script>
        function clicker() {
            alert("In clicker"); // this works
            document.getElementById('skip').onclick = function(e){
                alert("clicked"); // this works but the page still won't scroll to the "intro" div :(
            }
        }
        //clicker();
    </script>
</body>
</html>

Index.razor(@code 部分位於頁面頂部)

@page "/"
@code {
    [Inject]
    protected IJSRuntime JsRuntime { get; set; }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            JsRuntime.InvokeVoidAsync("clicker");
        }
    }
}

// This link won't go to the intro div when clicked :(
<a id="skip" class="skip" href="#intro">skip this bit</a>
...
<div id="intro" class="home">
...
</div>

啟動文件

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
    }

    public void Configure(IComponentsApplicationBuilder app)
    {
        app.AddComponent<App>("app");
    }
}

如果有人可以對此有所了解,那將節省我的一周。

這里不需要 JavaScript。

如果您將特定目標添加到您的標記中,它就會起作用。

您可以使用 target="_top" 來避免Blazor導航攔截。

<a class="skip" href="#intro" target="_top">skip this bit</a>
...
<div id="intro" class="home">
...
</div>

請注意, target="_top"只是指示瀏覽器在窗口的最頂層框架內導航,並不意味着您將滾動到頂部!

該頁面不會滾動到您在鏈接中指定的元素。這與 Blazor 和大多數其他 SPA 應用程序中路由的處理方式有關。 一個簡單的解決方案是您可以創建自己的 AnchorLink 組件並使用一點 JavaScript 互操作魔法。

AnchorLink.razorPages/Shared創建AnchorLink.razor

@code {

    public AnchorLink()
    {
        this.Attributes = new Dictionary<string, object>();
    }

    private string targetId = null;
    private bool preventDefault = false;

    /// <summary>
    /// This parameter supports arbitrary attributes.
    /// </summary>
    /// <remarks>
    /// Any attribute specified on the component, which is not defined as a parameter, whill be added to this dictionary.
    /// It is then uses as the source for attributes rendered onto the resulting HTML element below in the markup section
    /// of this component.
    /// For details, refer to <see cref="https://docs.microsoft.com/en-us/aspnet/core/blazor/components#attribute-splatting-and-arbitrary-parameters"/>.
    /// </remarks>
    [Parameter(CaptureUnmatchedValues = true)]
    public IDictionary<string, object> Attributes { get; set; }

    /// <summary>
    /// Supports child content for the component.
    /// </summary>
    /// <see cref="https://docs.microsoft.com/en-us/aspnet/core/blazor/components#child-content"/>
    [Parameter]
    public RenderFragment ChildContent { get; set; }

    [Inject]
    protected IJSRuntime JsInterop { get; set; }


    protected override void OnParametersSet()
    {
        string href = null;
        if (this.Attributes.ContainsKey("href"))
        {
            // If the href attribute has been specified, we examine the value of it. If if starts with '#'
            // we assume the rest of the value contains the ID of the element the link points to.
            href = $"{this.Attributes["href"]}";
            if (href.StartsWith("#"))
            {
                // If the href contains an anchor link we don't want the default click action to occur, but
                // rather take care of the click in our own method.
                this.targetId = href.Substring(1);
                this.preventDefault = true;
            }
        }
        base.OnParametersSet();
    }

    private async Task AnchorOnClickAsync()
    {
        if (!string.IsNullOrEmpty(this.targetId))
        {
            // If the target ID has been specified, we know this is an anchor link that we need to scroll
            // to, so we call the JavaScript method to take care of this for us.
            await this.JsInterop.InvokeVoidAsync("anchorLink.scrollIntoView", this.targetId);
        }
    }

}

<a href="" @onclick="this.AnchorOnClickAsync" @onclick:stopPropagation="false" />
<a @attributes="this.Attributes" @onclick="this.AnchorOnClickAsync" @onclick:preventDefault="this.preventDefault">Hello @this.ChildContent</a>

2.在wwwroot/Index.html js

<script src="_framework/blazor.webassembly.js"></script>
<script>
    window.anchorLink = {
    scrollIntoView: function (elementId) {
        // This function is called from the AnchorLink component using JavaScript interop.
        // It will try to find an element using the ID given to the function, and scroll that
        // element into view, if an element is found.
        var elem = document.getElementById(elementId);
        if (elem) {
            elem.scrollIntoView();
            window.location.hash = elementId;
        }
    }
}
</script>

Index.razor

<AnchorLink class="skip" href="#intro">skip this bit</AnchorLink>

參考https://mikaberglund.com/2019/12/28/creating-anchor-links-in-blazor-applications/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM