feat(module: back-top): display and disappear on scroll (#679)

Co-authored-by: James Yeung <shunjiey@hotmail.com>
This commit is contained in:
Brian Ding 2020-10-14 17:33:36 +08:00 committed by GitHub
parent 34fff47114
commit 20ec26034d
3 changed files with 41 additions and 5 deletions

View File

@ -1,7 +1,7 @@
@namespace AntDesign
@inherits AntDomComponentBase
@if (Visible)
@if (_visible)
{
<div class="@ClassMapper.Class" @onclick="_ => OnClickHandle()" style="@Style">
@if (ChildContent != null)

View File

@ -1,12 +1,14 @@
using System.Threading.Tasks;
using System.Text.Json;
using System.Threading.Tasks;
using AntDesign.JsInterop;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
namespace AntDesign
{
public partial class BackTop : AntDomComponentBase
{
private bool _visible = false;
[Inject]
public DomEventService DomEventService { get; set; }
@ -17,7 +19,7 @@ namespace AntDesign
public RenderFragment ChildContent { get; set; }
[Parameter]
public bool Visible { get; set; } = true;
public double VisibilityHeight { get; set; } = 400;
/// <summary>
/// 回到顶部的目标控件
@ -51,6 +53,19 @@ namespace AntDesign
base.OnInitialized();
}
protected async override Task OnFirstAfterRenderAsync()
{
if (string.IsNullOrWhiteSpace(TargetSelector))
{
DomEventService.AddEventListener("window", "scroll", OnScroll);
}
else
{
DomEventService.AddEventListener(TargetSelector, "scroll", OnScroll);
}
await base.OnFirstAfterRenderAsync();
}
protected void SetClass()
{
string prefixCls = "ant-back-top";
@ -58,5 +73,26 @@ namespace AntDesign
BackTopContentClassMapper.Add($"{prefixCls}-content");
BackTopIconClassMapper.Add($"{prefixCls}-icon");
}
private async void OnScroll(JsonElement obj)
{
JsonElement scrollInfo = await JsInvokeAsync<JsonElement>(JSInteropConstants.GetScroll);
double offset = scrollInfo.GetProperty("y").GetDouble();
_visible = offset > VisibilityHeight;
StateHasChanged();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (string.IsNullOrWhiteSpace(TargetSelector))
{
DomEventService.RemoveEventListerner<JsonElement>("window", "scroll", OnScroll);
}
else
{
DomEventService.RemoveEventListerner<JsonElement>(TargetSelector, "scroll", OnScroll);
}
}
}
}

View File

@ -7,7 +7,7 @@
<div>Scroll to bottom</div>
<div>Scroll to bottom</div>
<div>Scroll to bottom</div>
<BackTop TargetSelector="#target" Style="margin-bottom:60px" OnClick="OnClick">
<BackTop Style="margin-bottom:60px" OnClick="OnClick">
<div class="ant-back-top-inner">UP</div>
</BackTop>
</div>