侦听按键按下事件,剃刀

Listening to the keyPressed event, Razor

本文关键字:剃刀 事件      更新时间:2023-09-26
<body>
<table align="center" width="100%" height="100%">
    <tr>
        <td align="center" id="previousPhoto">
            @if (Model.HasPreviousPhoto)
            {
                if (Model.CurrentPhotoIndex == 0)
                {
                        <a href="@HrefHelper.ToPhoto(Model.Title, Model.CurrentPageIndex - 1, maxPhotosOnThePage)">
                            <section class="navSection">
                                <img class="previousPhoto" src="@Url.Content("~/Content/Icons/arrows.png")" />
                            </section>
                        </a>
                    }
                    else
                    {
                        <a href="@HrefHelper.ToPhoto(Model.Title, Model.CurrentPageIndex, Model.CurrentPhotoIndex - 1)">
                            <section class="navSection">
                                <img class="previousPhoto" src="@Url.Content("~/Content/Icons/arrows.png")" />
                            </section>
                        </a>
                    }
            }
            else
            {
                <section class="navSection"></section>
            }
        </td>
        <td class="photoPlaceholder" align="center">
            <section class="photoSection">
                <img src="@Model.CurrentPhoto.GenerateSrcHTML()" />
            </section>
        </td>
        <td align="center" id="nextPhoto">
            @if (Model.HasNextPhoto)
            {
                if (Model.CurrentPhotoIndex == maxPhotosOnThePage)
                {
                        <a href="@HrefHelper.ToPhoto(Model.Title, Model.CurrentPageIndex + 1, 0)">
                            <section class="navSection">
                                <img src="@Url.Content("~/Content/Icons/arrows.png")" />
                            </section>
                        </a>
                }
                else
                {
                        <a href="@HrefHelper.ToPhoto(Model.Title, Model.CurrentPageIndex, Model.CurrentPhotoIndex + 1)">
                            <section class="navSection">
                                <img src="@Url.Content("~/Content/Icons/arrows.png")" />
                            </section>
                        </a>
                }
            }
            else
            {
                <section class="navSection"></section>
            }
        </td>
    </tr>
</table>

现在我需要侦听左/右箭头键向下事件,并触发与这些链接相同的操作。据我了解,没有JS的帮助就无法做到这一点,对吧?我对 ASP.NET,尤其是JS很陌生,所以你们中的某个人可以告诉我实现上述目标的最佳方法吗?

您需要在视图中添加 js 片段

<script>
    document.addEventListener('keydown', function(e){
        //37 is left arrow, 39 is right arrow
        if(e.which === 37){
            document.getElementById('previousPhoto').getElementsByTagName('a')[0].click();
        } else if (e.which === 39) {
            document.getElementById('nextPhoto').getElementsByTagName('a')[0].click();
    }
});
</script>