小编Cod*_*ewb的帖子

在 Blazor 组件中使用 Javascript addEventListener

我有一个在服务器端呈现的 Blazor 组件。我想在里面有一些可折叠的div。然而,由于代码是服务器渲染的,因此不会执行 Javascript,因此这些部分不会崩溃。

这是我的文件中的代码script.js

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var content = this.nextElementSibling;
        if (content.style.maxHeight){
            content.style.maxHeight = null;
        } else if(window.matchMedia("(max-width:1440px)")){
            // content.style.maxHeight = content.scrollHeight + "px";
            content.style.maxHeight = "20vh";
        } 
        else {
            content.style.maxHeight = "50vh";
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

这是我的main.cshtml文件:

<component type="typeof(Main)" render-mode="Server" />

<script src="~/js/script.js" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)

最后是我的Main带有可折叠部件的组件:

@using Microsoft.AspNetCore.Components;
@using Microsoft.AspNetCore.Components.Web;

<div class="collapsible">
    <label for="tutu">HEADER</label>
    <div id="mybtn" class="btn-rch"></div> …
Run Code Online (Sandbox Code Playgroud)

c# blazor blazor-server-side blazor-jsinterop

1
推荐指数
1
解决办法
1647
查看次数

标签 统计

blazor ×1

blazor-jsinterop ×1

blazor-server-side ×1

c# ×1