问题描述
我有 2 个组件,一个希望在浏览器为移动设备时显示,另一个在平板电脑/台式机上显示.
I have 2 components, one that I wish to display if the browser is Mobile, the other if it is tablet/desktop.
@if(isMobile)
{
<MobileComponent />
}
else
{
<DesktopComponent />
}
我希望在桌面上根本没有 DOM 中的移动组件,反之亦然,所以我不想做 CSS 可见性.我宁愿只渲染一个.确定浏览器是否为移动浏览器以便我可以相应地设置 isMobile 的最佳方法是什么?
I am looking to not have the Mobile Component in the DOM at all when on desktop and vice versa so i dont want to do a CSS visibility. Id rather only the one be rendered. What is the best approach to determine if the browser is a Mobile browser so I can set isMobile accordingly?
推荐答案
这是我创建的方法.使用以下函数将 js 添加到您的 Index.html 页面
Here is the method that I created. Add js to your Index.html page with the following function
<script>
function isDevice() {
return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile/i.test(navigator.userAgent);
}
</script>
然后在您想知道浏览器是否为移动设备的任何组件上添加以下内容
Then on any component where you want to know if the browser is mobile add the following
protected override async Task OnInitializedAsync()
{
IsMobile = await JSRuntime.InvokeAsync<bool>("isDevice");
}
如果您使用 Chrome 进行调试,当您将浏览器设置为移动设备时,该值将为 true
If you are using Chrome to debug, when you set the browser to mobile the value will be true
这篇关于Blazor 仅在移动设备上显示组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!