Compare commits

...

7 Commits

Author SHA1 Message Date
fc407935d2 chore :悬浮按钮自定义 2026-10-12 17:45:04 +08:00
df5be6045b common\js\floating-button.js
common\js\startup-ad.js
components\ns-mp-navbar\ns-mp-navbar.vue
2026-10-12 15:41:28 +08:00
571452cd30 chore:悬浮按钮可以自定义调节 2026-10-12 15:37:38 +08:00
1c0444b1ec chore:微信小程序真机广告 正常 2026-10-10 17:31:02 +08:00
09909f0dcf chore:真机上显示广告正常 2026-10-10 16:02:20 +08:00
b14032149e chore:启动广告,后台开启首次弹出,第一次进入小程序后会弹出广告,
后台开启每次弹出,每次重新进入小程序都会弹出广告
2026-10-10 11:35:55 +08:00
447f7cd7b5 chore:启动广告,后台开启首次弹出,每一次重新进入小程序后都会弹出广告 2026-10-10 11:20:36 +08:00
10 changed files with 893 additions and 101 deletions

View File

@@ -257,7 +257,7 @@ const localDevConfig = ({
// })['2811']; // 本地
// })['5g-317']; // 电磁兼容
// })['5g-351']; //
})['2881']; // 本地
})['5g-97']; // 本地
// })['local-2']; // 本地
// })['local-11']; // 本地
// })['1-test']; // test

View File

@@ -8,6 +8,7 @@
// PR-MULTI-TURN-KEY-BINDING (2026-09-18): AI 客服会话 key 切换
// 登录态恢复后通知 aiService 清旧 user key,避免串会话
import aiService from 'common/js/ai-service.js';
import { markNeedStartupAd } from 'common/js/startup-ad.js';
// 记录 App 是否已至少展示过一次: 首次 onShow = 启动展示(由 onLaunch 完成初始化),
// 之后每一次 onShow(含微信 ... 菜单"重新进入小程序"、从后台切回)都视为"重新进入"。
@@ -512,6 +513,8 @@
// 之后每次 onShow(含 ... 重新进入、从后台切回前台)都视为重新进入,主动失效缓存并重新对齐。
if (_appHasShown) {
try { Lang.onAppReentry(); } catch (e) {}
// 重新进入小程序(从后台切回 / "重新进入小程序"菜单): 标记需要弹出启动广告
try { markNeedStartupAd(); } catch (e) {}
}
_appHasShown = true;

View File

@@ -2,6 +2,7 @@ import WxMap from 'common/js/map-wx-jssdk.js';
import Config from '@/common/js/config.js';
import util from '@/common/js/util.js';
import { classifyHttpError, httpErrorKey } from '@/common/js/http-error.js';
import { consumeNeedStartupAd, isColdLaunchPending } from '@/common/js/startup-ad.js';
let systemInfo = util.getDeviceInfo();
@@ -297,25 +298,84 @@ export default {
data: {},
async: false
});
this.adv = res.value
// 弹框形式,首次弹出 1,每次弹出 0
// 接口把启动广告配置放在 data 字段(少数环境也可能放在 value), 两者兼容,
// 避免取到 undefined 后模板 v-if 抛错导致 uni-popup 不渲染、真机广告弹不出来
let advData = (res && (res.data != null ? res.data : res.value)) || {};
this.adv = advData;
// 后台配置: advshow=1 开启启动广告; advtype 决定弹出策略
// advtype == 1: 首次弹出 —— 仅第一次进入小程序弹出(持久化标记, 清缓存后可再弹)
// advtype == 0: 每次弹出 —— 每次"重新进入小程序"都弹出(不含 Tab 切换回首页)
if (this.adv.advshow == 1) {
setTimeout(() => {
if (res.value.advtype == 1) {
var popwindow_count = uni.getStorageSync(this.id + this.name + '_popwindow_count');
if ((this.$refs.uniPopupWindow && popwindow_count == '') || (
this.$refs.uniPopupWindow && popwindow_count == 1)) {
setTimeout(async () => {
// 隐私协议未同意时, 先等用户点击隐私协议(同意/拒绝)关闭弹窗,
// 否则广告弹窗会被隐私弹窗(z-index:5000)盖住, 真机上表现为"点了隐私协议后广告不弹"
await this._waitPrivacyResolved();
if (!this.$refs.uniPopupWindow) return;
this.$refs.uniPopupWindow.open();
uni.setStorageSync(this.id + this.name + '_popwindow_count', 1);
// 先判定本次是否需要弹出, 避免无谓的图片预加载
let shouldOpen = false;
let isFirstType = false;
if (this.adv.advtype == 1) {
// 首次弹出: 从未展示过才弹
var popwindow_count = uni.getStorageSync(this.id + this.name + '_popwindow_count');
if (popwindow_count == '' || popwindow_count == 0) {
shouldOpen = true;
isFirstType = true;
}
} else if (res.value.advtype == 0) {
this.$refs.uniPopupWindow.open();
uni.setStorageSync(this.id + this.name + '_popwindow_count', 0);
} else {
// 每次弹出: 冷启动首次 或 真正"重新进入小程序"(App 前后台切换)时弹出,
// 由 App.onShow 在重新进入时置位的信号驱动, 切 Tab 不会触发 App.onShow 故不弹
if (consumeNeedStartupAd() || isColdLaunchPending()) {
shouldOpen = true;
}
}
if (!shouldOpen) return;
// 关键: 广告图片是网络图, 而 uni-popup 用 v-if 在 open() 时才渲染 slot,
// 图片要等弹窗打开后才开始请求/解码, 真机网络慢时就会"一截一截"逐步显示。
// 先把所有广告图片预加载进本地缓存, 全部就绪后再 open, 使弹窗一次性完整出现。
await this._preloadAdvImages(this.adv.list);
if (!this.$refs.uniPopupWindow) return;
this.$refs.uniPopupWindow.open();
if (isFirstType) {
uni.setStorageSync(this.id + this.name + '_popwindow_count', 1);
}
}, 500);
}
},
/**
* 等待隐私协议流程结束后再弹启动广告
* - 鸿蒙元服务: 隐私由系统托管, 应用层不弹自建弹窗, 直接放行
* - 已同意过(storage privacyAgreed): 无需等待, 直接放行
* - 未同意: 监听 PrivacyManager 广播的 privacy:agreed / privacy:disagreed,
* 用户点击隐私协议(同意/拒绝)关闭弹窗后放行
* - 兜底超时: 隐私协议因规则未弹等情况永不 emit 时也要弹广告, 避免卡死
* @param {number} [maxWait=15000]
* @returns {Promise<void>}
*/
_waitPrivacyResolved(maxWait = 15000) {
// 鸿蒙元服务: 隐私协议由系统托管, 应用层不弹自建隐私弹窗, 无需等待
// #ifdef MP-HARMONY
return Promise.resolve();
// #endif
// 已经同意过 → 隐私弹窗不会再出现, 直接放行
if (uni.getStorageSync('privacyAgreed')) return Promise.resolve();
return new Promise((resolve) => {
let done = false;
const finish = () => {
if (done) return;
done = true;
uni.$off('privacy:agreed', finish);
uni.$off('privacy:disagreed', finish);
clearTimeout(timer);
resolve();
};
uni.$on('privacy:agreed', finish);
uni.$on('privacy:disagreed', finish);
// 兜底: 隐私协议因规则未弹 / 一直未处理时, 超时后也要弹广告
const timer = setTimeout(finish, maxWait);
});
},
// 无法从网络获取 diy 数据时:在页面内渲染错误横幅(各端可靠、一定可见)
// 同时通过 uni.$emit 通知 splash-state 关闭启动屏 (否则 strict 模式永远不关)
@@ -542,9 +602,46 @@ export default {
console.warn('[DIY][getDiyInfo] no value in res.data', JSON.stringify(diyDataValue).slice(0, 200));
}
},
/**
* 预加载启动广告图片
* 广告弹窗由 uni-popup 在 open() 时才用 v-if 渲染内容, 图片是网络图,
* 若等到弹窗打开后才开始加载, 真机网络慢时会出现"一截一截"逐步显示。
* 这里提前把图片下载进本地缓存, 等全部加载完成(或超时)后再弹出,
* 使弹窗一次性完整呈现。
* @param {Array} list - adv.list, 元素形如 { imageUrl, link }
* @param {number} [timeout=4000] - 单张兜底超时, 避免个别图片卡住导致广告永不弹出
* @returns {Promise<void>}
*/
_preloadAdvImages(list, timeout = 4000) {
if (!list || !list.length) return Promise.resolve();
const tasks = list.map((item) => {
return new Promise((resolve) => {
const url = (item && item.imageUrl) ? this.$util.img(item.imageUrl) : '';
if (!url) return resolve();
let done = false;
const finish = () => {
if (done) return;
done = true;
clearTimeout(timer);
resolve();
};
const timer = setTimeout(finish, timeout);
try {
// getImageInfo 会下载图片并写入本地缓存, 之后 image 组件可直接命中缓存
uni.getImageInfo({
src: url,
success: finish,
fail: finish
});
} catch (e) {
finish();
}
});
});
return Promise.all(tasks).then(() => {});
},
closePopupWindow() {
this.$refs.uniPopupWindow.close();
uni.setStorageSync(this.id + this.name + '_popwindow_count', -1);
},
closeCollectPopupWindow() {
this.$refs.collectPopupWindow.close();

View File

@@ -68,6 +68,10 @@ export default {
hover_nav_bg_color: '#FFFC',
hover_nav_text_color: '#000',
hover_nav_font_size: '36rpx', // 悬浮按钮内文字/图标字号(后台可自定义, 默认与图标 36rpx 对齐)
hover_nav_lang_font_size: '36rpx', // 语言按钮内文字字号基准(文字实际按 0.667 缩放)
hover_nav_kefu_font_size: '36rpx', // 客服按钮内图标/emoji字号基准
hover_nav_phone_font_size: '36rpx', // 电话按钮内图标字号基准
// ===== DIY 分类页字号 token =====
diy_category_tree_select_size: '28rpx',

View File

@@ -0,0 +1,134 @@
/**
* 浮动侧边栏配置消费 (字段来源: /api/config/init → data.floating_button)
* 纯函数模块, 无副作用, 可直接单测
*/
/** 归一化路由: 'pages/index/index' → '/pages/index/index' */
export function normalizeRoute(route) {
if (!route) return '';
return String(route).charAt(0) === '/' ? String(route) : '/' + String(route);
}
/** 取当前页面路由 (兼容 H5 / 小程序; route 已含分包 root, 如 'pages_goods/detail') */
export function getCurrentRoute() {
try {
const pages = getCurrentPages();
const cur = pages[pages.length - 1];
return normalizeRoute((cur && (cur.route || (cur.$page && cur.$page.path))) || '');
} catch (e) {
return '';
}
}
/**
* 前缀命中判定
* '/pages/index' 命中 '/pages/index' 与 '/pages/index/xxx'
* '/pages_tool/' 命中 '/pages_tool/xxx' (前缀自带尾 /)
* '/pages/order/payment' 只命中它自己及其子路径
*/
export function hitPrefix(route, prefix) {
if (!route || !prefix) return false;
const p = prefix.charAt(prefix.length - 1) === '/' ? prefix : prefix + '/';
return route === prefix || route.indexOf(p) === 0;
}
/** 任一前缀命中 */
function hitAny(route, prefixes) {
if (!Array.isArray(prefixes)) return false;
for (let i = 0; i < prefixes.length; i++) {
if (hitPrefix(route, prefixes[i])) return true;
}
return false;
}
/** 找出路由命中的页面分组 key (未命中返回 null) */
export function matchPageGroup(route, prefixMap) {
if (!prefixMap) return null;
const keys = Object.keys(prefixMap);
for (let i = 0; i < keys.length; i++) {
if (hitAny(normalizeRoute(route), prefixMap[keys[i]])) return keys[i];
}
return null;
}
/**
* 侧边栏在当前页面是否显示 —— 唯一判定入口
*
* 优先级: 总开关 → 强制隐藏 → 显示范围
* 1) fb 不存在 (老缓存响应) → fallbackVisible (默认 true, 保持老行为)
* 2) enabled != 1 → false
* 3) 命中 force_hidden_prefixes 任意前缀 → false (最高优先级)
* 4) 命中 custom_pages / page_prefixes._custom → true
* 5) 命中 pages[组] == 1 → true
* 6) 都不命中 (如 /pages_goods/*) → false
*/
export function shouldShowOnPage(fb, route, fallbackVisible) {
if (!fb || typeof fb !== 'object') return fallbackVisible !== false;
if (Number(fb.enabled) !== 1) return false;
const r = normalizeRoute(route);
if (!r) return false;
// 强制隐藏 — 优先级最高
if (matchPageGroup(r, fb.force_hidden_prefixes)) return false;
// 自定义前缀优先判定
if (hitAny(r, fb.custom_pages) || hitAny(r, (fb.page_prefixes || {})['_custom'])) return true;
// 预设分组
const group = matchPageGroup(r, fb.page_prefixes);
if (group) return Number((fb.pages || {})[group]) === 1;
return false;
}
/**
* 当前页面要渲染的按钮列表 (已按 button_order 排序 + 显隐过滤)
* 返回 ['lang','kefu','phone'] 的子集, 空数组 = 整个侧边栏不渲染
* 返回 null = 配置缺失, 由调用方决定老行为
*/
export function resolveVisibleButtons(fb) {
if (!fb || typeof fb !== 'object') return null;
const order = Array.isArray(fb.button_order) ? fb.button_order : ['lang', 'kefu', 'phone'];
const map = fb.buttons || {};
const out = [];
for (let i = 0; i < order.length; i++) {
const k = order[i];
if (Number(map[k]) === 1) out.push(k);
}
return out;
}
/**
* 语言按钮显示文案
* @param {Object} fb data.floating_button
* @param {Array} langList [{ value:'zh-cn', name:'CN' }, ...]
* @param {Number} currentIdx 当前语言下标
*/
export function resolveLangButtonText(fb, langList, currentIdx) {
const list = Array.isArray(langList) ? langList : [];
if (!list.length) return '';
const style = (fb && fb.lang_switch && fb.lang_switch.style) || 'target';
if (style === 'text') {
const t = (fb && fb.lang_switch && fb.lang_switch.text) || '';
if (t) return t; // 空文案兜底走 target
}
if (style === 'current' || list.length < 2) {
return (list[currentIdx] && list[currentIdx].name) || '';
}
// target: 显示「点下去会切到的那个」语言
// 2 种语言 → 另一个; >2 种 → 取第一个不是当前的那个
let targetIdx = 0;
for (let i = 0; i < list.length; i++) {
if (i !== currentIdx) { targetIdx = i; break; }
}
return list[targetIdx] ? (list[targetIdx].name || '') : '';
}
/** 语言切换按钮是否可见 (含老「双语模式」fallback) */
export function isLangButtonVisible(fb, shopInfo, langCount) {
if (Number(langCount) < 2) return false;
if (fb && fb.lang_switch) return Number(fb.lang_switch.enabled) === 1;
return !!(shopInfo && shopInfo.ischina); // 老行为兜底
}

30
common/js/startup-ad.js Normal file
View File

@@ -0,0 +1,30 @@
// 启动广告弹出信号
// 用于判定"当前是否需要弹出启动广告":
// - 小程序冷启动(首次进入): 由模块级 _coldLaunchedShown 标记判定, 整个 app 进程只记一次
// - 小程序重新进入(从后台切回 / 微信"重新进入小程序"菜单):
// 由 App.onShow 在"非首次展示"时调用 markNeedStartupAd() 置位
// 信号消费一次即清除, 不落地到持久化存储, 因此无需清缓存即可每次重新进入都弹出。
// 关键: 切换 Tab 回到首页只触发"页面级 onShow", 不会触发 App.onShow, 也不会重置
// 模块级冷启动标记, 因此不会在 Tab 切换时误弹。
let _needStartupAd = false;
let _coldLaunchedShown = false;
// App 层检测到"重新进入小程序"时调用, 标记本次需要弹出启动广告
export function markNeedStartupAd() {
_needStartupAd = true;
}
// 页面层读取并消费该信号(消费后自动复位)
export function consumeNeedStartupAd() {
const v = _needStartupAd;
_needStartupAd = false;
return v;
}
// 是否为本 app 进程的首次冷启动(只返回一次 true, 之后恒为 false)
export function isColdLaunchPending() {
if (_coldLaunchedShown) return false;
_coldLaunchedShown = true;
return true;
}

View File

@@ -62,7 +62,13 @@ export default {
},
...{
hover_nav_bg_color: '#FFFC', //背景色: 红色 '#c6251b', 白色: '#FFFC'
hover_nav_text_color: '#000' // 文字颜色: 白色 '#FFFFFF', 黑色: '#000'
hover_nav_text_color: '#000', // 文字颜色: 白色 '#FFFFFF', 黑色: '#000'
hover_nav_font_size: '36rpx', // 悬浮按钮内文字/图标字号(后台可自定义, 默认与图标 36rpx 对齐)
// ===== 逐按钮字号(与 hover_nav_lang/kefu/phone 的 bg/text/size 同约定, 基准 36rpx) =====
// 未单独配置时回退到上面的 hover_nav_font_size(全局旋钮)
hover_nav_lang_font_size: '36rpx', // 语言按钮内文字字号基准(文字实际按 0.667 缩放)
hover_nav_kefu_font_size: '36rpx', // 客服按钮内图标/emoji字号基准
hover_nav_phone_font_size: '36rpx' // 电话按钮内图标字号基准
},
// ===== DIY 分类页字号 token(全 8 preset 一致, 远端可覆写) =====

View File

@@ -4,6 +4,7 @@
<view v-if="(pageCount === 1 || need) && fbVisible && hasAnyButton" class="fixed-box"
:style="[customContainerStyle, {
height: containerHeight,
width: containerWidth,
bottom: containerBottom,
right: containerRight,
backgroundImage: bgUrl ? `url(${bgUrl})` : '',
@@ -12,8 +13,8 @@
<!-- 多语言切换按钮:根据语言数智能切换交互 -->
<view
v-if="isLanguageSwitchEnabled && hasLangButton"
class="btn-item common-bg"
:style="[btnItemStyle, { order: orderIndex.lang }]"
class="btn-item common-bg btn-lang"
:style="[btnItemStyle('lang'), { order: orderIndex.lang }]"
@click="handleLangButtonClick"
>
<view class="lang-btn-text">{{ langButtonText }}</view>
@@ -21,8 +22,8 @@
<!-- 微信官方客服按钮-->
<button
v-if="hasKefuButton && hasValidKefuConfig && isWeappOfficialKefu"
class="btn-item common-bg"
:style="[btnItemStyle, { order: orderIndex.kefu }]"
class="btn-item common-bg btn-kefu"
:style="[btnItemStyle('kefu'), { order: orderIndex.kefu }]"
open-type="contact"
>
<text class="icox icox-kefu" v-if="!kefuimg"></text>
@@ -31,8 +32,8 @@
<!-- 其他类型客服按钮(智能客服、企业微信等)-->
<view
v-if="hasKefuButton && hasValidKefuConfig && !isWeappOfficialKefu && !showWeappSystemKefu"
class="btn-item common-bg"
:style="[btnItemStyle, { order: orderIndex.kefu }]"
class="btn-item common-bg btn-kefu"
:style="[btnItemStyle('kefu'), { order: orderIndex.kefu }]"
@click="handleUnifiedKefuClick"
>
<image
@@ -49,8 +50,8 @@
<!-- 智能客服按钮(当同时显示小程序系统客服时)-->
<view
v-if="hasKefuButton && hasValidKefuConfig && !isWeappOfficialKefu && showWeappSystemKefu"
class="btn-item common-bg"
:style="[btnItemStyle, { order: orderIndex.kefu }]"
class="btn-item common-bg btn-kefu"
:style="[btnItemStyle('kefu'), { order: orderIndex.kefu }]"
@click="handleUnifiedKefuClick"
>
<image
@@ -67,8 +68,8 @@
<!-- 小程序系统客服按钮 -->
<button
v-if="hasKefuButton && hasValidKefuConfig && showWeappSystemKefu"
class="btn-item common-bg"
:style="[btnItemStyle, { order: orderIndex.kefu }]"
class="btn-item common-bg btn-kefu"
:style="[btnItemStyle('kefu'), { order: orderIndex.kefu }]"
open-type="contact"
>
<text class="icox icox-kefu" v-if="!kefuimg"></text>
@@ -77,8 +78,8 @@
<!-- 电话按钮 -->
<view
v-if="hasPhoneButton"
class="btn-item common-bg"
:style="[btnItemStyle, { order: orderIndex.phone }, { backgroundImage: phoneimg ? `url(${phoneimg})` : '', backgroundSize: '100% 100%' }, customButtonStyle]"
class="btn-item common-bg btn-phone"
:style="[btnItemStyle('phone'), { order: orderIndex.phone }, { backgroundImage: phoneimg ? `url(${phoneimg})` : '', backgroundSize: '100% 100%' }, customButtonStyle]"
@click="call"
>
<text class="iconfont icon-dianhua" v-if="!phoneimg"></text>
@@ -165,6 +166,20 @@ function getLangShortCode(langValue, customMap) {
return prefix.toUpperCase();
}
// 跨页面/重挂载复用的悬浮按钮避让值(设计稿 rpx)。
// H5 切换页面时 hover-nav 会重新挂载并重新测量公告栏: 无公告栏的页面(如分类页)
// noticeRect 为 null, 若直接回落基础位置, 会与首页"公告下方"位置不一致,
// 切回首页时按钮突然上/下跳。缓存上次算出的避让值, 让所有页面位置恒定。
let cachedAvoidBottom = null;
// 需要隐藏悬浮按钮的页面路由(全平台生效: H5 + 小程序)
// /pages_goods/category 商品分类
// /pages_tool/contact/contact 电子名片(名片)
const H5_HIDDEN_ROUTES = [
'/pages_goods/category',
'/pages_tool/contact/contact',
];
export default {
name: 'hover-nav',
mixins: [i18nLazyMixin],
@@ -194,6 +209,12 @@ export default {
layoutTopBottom: 272, // --top-btn-bottom
layoutTopSize: 72, // --top-btn-size(Top 按钮正方形边长)
layoutFloatingWidth: 100, // --floating-btn-width
// 公告栏(diy-notice 跑马灯)实时测量数据,用于把悬浮按钮避让到其下方
// 注意: 字段名不能带 _ 前缀 —— Vue 2 不代理 _/$ 开头的 data 属性,
// 也不具备响应式,计算属性将永远读不到测量结果(踩过的坑)
noticeRect: null, // {top,bottom,height} 视口坐标(px)
winW: 0, // 视口宽(px)
winH: 0, // 视口高(px)
// i18n-lazy mixin 要求:data 中预声明 i18n 字段(初值空串),
// 模板只读 this.i18n.xxx,真实翻译在 openLangPicker() 中 prepareI18n() 后才填入
i18n: {
@@ -250,8 +271,14 @@ export default {
fbConfig() {
return (this.$store && this.$store.state && this.$store.state.floatingButtonConfig) || null;
},
// 指定页面隐藏悬浮按钮(商品分类 / 电子名片), 全平台生效
hiddenOnRoute() {
const r = this.currentRoute;
return H5_HIDDEN_ROUTES.some((p) => r === p || r.indexOf(p + '/') === 0);
},
// 总开关 + 强制隐藏 + 页面范围 判定结果
fbVisible() {
if (this.hiddenOnRoute) return false; // 指定页面直接隐藏
return shouldShowOnPage(this.fbConfig, this.currentRoute, true);
},
// 最终要渲染的按钮 (已按 button_order 排序 + 显隐过滤); null = 用老行为
@@ -296,28 +323,14 @@ export default {
// 1) 测试发现 .btn-item 的 min-*/max-*/aspect-ratio/flex-shrink 等 !important
// 规则在 scoped 样式下,被某些 flex 布局的隐式约束吃掉,只 width/height/border-radius
// 生效,导致高度被压缩成 39.5px(从 41px),按钮显示为轻微椭圆。
// 2) inline-style 优先级高于 CSS class,直接锁死 72x72 + 正圆。
// 3) 用 max-width/max-height + flex-shrink 0 三重兜底,防止被任何层级的样式覆盖。
btnItemStyle() {
return {
width: '72rpx',
height: '72rpx',
'min-width': '72rpx',
'min-height': '72rpx',
'max-width': '72rpx',
'max-height': '72rpx',
'aspect-ratio': '1',
// border-radius 保留作 clip-path 不支持时的 fallback
'border-radius': '50%',
'flex-shrink': '0',
'flex-grow': '0',
'align-self': 'center',
'box-sizing': 'border-box',
padding: '0',
margin: '14rpx 0',
overflow: 'hidden',
};
},
// 2) inline-style 优先级高于 CSS class,直接锁死按钮尺寸 + 正圆。
// 3) 尺寸来源(逐按钮可调, 见 btnSizeRpx):
// hover_nav_lang_btn_size / hover_nav_lang_size
// hover_nav_kefu_btn_size / hover_nav_kefu_size
// hover_nav_phone_btn_size / hover_nav_phone_size
// 未配置时回退 72rpx(与原行为一致)。
// 4) 用 max-width/max-height + flex-shrink 0 三重兜底,防止被任何层级的样式覆盖。
// (已从 computed 改为 method: 模板按按钮类型调用 btnItemStyle('lang'|'kefu'|'phone'))
unreadCount() {
const customerService = createCustomerService(this);
return customerService.getUnreadCount();
@@ -351,53 +364,101 @@ export default {
return customerService.hasValidKefuConfig();
},
//根据显示的按钮数量动态计算容器高度
// 计算明细(buttonCount 按钮场景):
// 每个按钮槽位:72rpx(按钮,与 to-top 一致) + 14rpx(上 margin) + 14rpx(下 margin) = 100rpx
// 容器 padding:20rpx 上 + 20rpx 下 = 40rpx
// 总高度 (rpx):buttonCount × 100 + 40
// 新配置生效时按 visibleButtons 的实际按钮数算,避免隐藏按钮后留下空白档;
// 全部按钮被关掉时返回 0rpx(根节点 v-if 已含 hasAnyButton, 这里是双保险);
// 配置缺失(fbConfig 为 null)时保持老行为: 电话恒显 + 可选语言 + 可选系统客服。
// extraKefuSlot: 小程序系统客服与客服主按钮并存时模板会多渲染一个按钮,
// 需要为它多留一个槽位(fallback 分支与老逻辑等价)。
containerHeight() {
// 当前实际会渲染出来的按钮尺寸列表(rpx), 与模板渲染一一对应。
// containerHeight / containerWidth 都以它为准, 后台把任一按钮调多大都能撑开容器。
renderedBtnSizes() {
const b = this.visibleButtons;
if (b && b.length === 0) return '0rpx';
if (b && b.length === 0) return [];
const extraKefuSlot = (this.hasKefuButton && this.showWeappSystemKefu) ? 1 : 0;
const buttonCount = b
? b.length + extraKefuSlot
: 1 + (this.isLanguageSwitchEnabled ? 1 : 0) + extraKefuSlot;
const totalRpx = buttonCount * 100 + 40;
return `${totalRpx}rpx`;
const sizes = [];
if (this.isLanguageSwitchEnabled && this.hasLangButton) {
sizes.push(this.btnSizeRpx('lang'));
}
if (this.hasKefuButton && this.hasValidKefuConfig) {
sizes.push(this.btnSizeRpx('kefu'));
// 小程序系统客服与客服主按钮并存时, 模板会多渲染一个按钮
if (this.showWeappSystemKefu && !this.isWeappOfficialKefu) {
sizes.push(this.btnSizeRpx('kefu'));
}
}
if (this.hasPhoneButton) {
sizes.push(this.btnSizeRpx('phone'));
}
return sizes;
},
// 根据显示的按钮数量与各自尺寸动态计算容器高度
// 每个按钮槽位 = 按钮尺寸 + 14rpx(上 margin) + 14rpx(下 margin)
// 容器 padding: 20rpx 上 + 20rpx 下 = 40rpx
// 旧公式 buttonCount*100+40 是"所有按钮 72rpx"的特例, 现按逐按钮实际尺寸累加
containerHeightNum() {
const sizes = this.renderedBtnSizes;
if (sizes.length === 0) return 0;
return sizes.reduce((sum, s) => sum + s + 28, 0) + 40;
},
containerHeight() {
return this.rpxStr(this.containerHeightNum);
},
// 容器宽度自适应: 至少保持原 --floating-btn-width(100rpx) 布局不变;
// 后台把任一按钮调大(如 hover_nav_lang_btn_size=120rpx)时, 容器随之撑大,
// 否则 .fixed-box 的 overflow:hidden 会把超宽按钮裁剪变形。
containerWidthNum() {
const maxBtn = this.renderedBtnSizes.reduce((m, s) => Math.max(m, s), 0);
// 额外 +12rpx 呼吸余量: 避免 rpx→px 亚像素取整导致按钮与容器边缘严丝合缝,
// 也给 bgUrl 背景胶囊留出按钮两侧各 6rpx 的边距; 按钮由 flex 居中, 不影响对齐。
return Math.max(this.layoutFloatingWidth, maxBtn + 12);
},
containerWidth() {
return this.rpxStr(this.containerWidthNum);
},
// 浮动按钮组底部 bottom 动态计算(在 Top 按钮上方):
// Top 按钮是 72x72 正方形,顶部边界 = bottom + size = layoutTopBottom + layoutTopSize
// containerBottom = Top 顶部边界 + space
// ------------------------------------------------------------
// space 是经验调优值(非数学推导),手调结果:
// H5 : 18 * 5 = 90rpx
// MP-WEIXIN: 18 * 1 = 18rpx
// 为什么 H5 反而大、微信反而小:
// 虽然 rpx 单位定义相同(windowWidth/750),但 Top 按钮
// <image mode="widthFix"> 在不同平台渲染有视觉差异。
// H5 浏览器(WebKit/Blink)渲染时,图片元素可能保留更多
// 内边距/基线,视觉上比 72rpx 大,需要更大间距才不挤;
// 微信 Skia 严格按 width=72rpx 渲染,视觉紧凑,
// 18rpx 就能有清晰的呼吸感。
// 90/18 是按"视觉上不挤"原则手调出来的,反过来都不行。
// space 两端统一为 18rpx:
// 旧的 H5=90rpx 特调是"H5 内联 rpx 全部失效、实际走 CSS fallback"年代的产物;
// 现在内联样式经 rpxStr() 在 H5 输出精确 px,几何计算两端一致,
// H5 必须与微信小程序保持相同位置(272+72+18 = 362rpx),不再需要平台特调。
// ------------------------------------------------------------
// 注意:安全区 var(--window-bottom) 由 CSS 的 margin-bottom 统一处理,
// 与 Top 按钮的 .mescroll-totop { margin-bottom: var(--window-bottom) } 一致,
// 两者会被安全区同步上推,space 保持不变
containerBottom() {
let space = 18 * 5;
// #ifdef MP-WEIXIN
space = 18 * 1;
// #endif
return `${this.layoutTopBottom + this.layoutTopSize + space}rpx`;
const space = 18;
const base = this.layoutTopBottom + this.layoutTopSize + space;
// 避让公告栏(diy-notice 跑马灯): 把悬浮按钮整体放到公告栏"正下方"。
// 关键:用「文档坐标」而非「视口坐标」算 bottom ——
// 公告栏随页面内容滚动, 其视口坐标(rect.bottom)随滚动变化;
// 若直接 (winH - rect.bottom) 算, 滚动时按钮会跟着公告栏上下移动。
// 这里把 rect 加上当前滚动距离得到"公告栏在文档中的底边",
// 再算 (winH - 文档底边): 该值与滚动无关, 按钮固定在"页面顶部时公告栏正下方",
// 滚动时按钮静止(公告栏自行滚走), 不再来回滑动。
const rect = this.noticeRect;
let target = null;
if (rect && this.winW > 0 && this.winH > 0 && rect.bottom > 0 && rect.top < this.winH) {
// 当前滚动距离(H5: window.pageYOffset; 小程序无 window 时回退 0)
let scrollY = 0;
try {
if (typeof window !== 'undefined' && 'pageYOffset' in window) {
scrollY = window.pageYOffset || 0;
} else if (typeof document !== 'undefined' && document.documentElement) {
scrollY = document.documentElement.scrollTop || 0;
}
} catch (e) { scrollY = 0; }
const scaleInv = 750 / this.winW; // px → 设计稿 rpx
const gap = 12; // 按钮与公告栏之间的间距(设计稿 rpx)
// 公告栏底边在文档中的坐标 = 视口坐标 + 滚动距离(滚动无关, 恒定)
const docBottom = rect.bottom + scrollY;
const distFromBottom = (this.winH - docBottom) * scaleInv;
// 按钮 bottom = 文档底边距视口底部 + 间距 - 按钮自身高度
const below = distFromBottom - gap - this.containerHeightNum;
if (Number.isFinite(below)) {
target = Math.max(0, below);
cachedAvoidBottom = target; // 缓存: 跨页面/重挂载复用, 位置恒定
}
}
// 无公告栏的页面(如分类页)复用上一次算出的避让值, 使悬浮按钮在所有页面位置一致
if (target === null && cachedAvoidBottom !== null) target = cachedAvoidBottom;
return this.rpxStr(target === null ? base : target);
},
// 浮动按钮组水平 right 动态计算(与 Top 按钮中心对齐):
// 公式: containerRight = TopRight + TopSize/2 - FloatingWidth/2
@@ -412,8 +473,10 @@ export default {
// - right edge 对齐(46rpx):左侧突出 28rpx,中心错位 14rpx
// center 对齐不仅中心精准,突出量也更小
containerRight() {
const offset = this.layoutTopRight + this.layoutTopSize / 2 - this.layoutFloatingWidth / 2;
return `${offset}rpx`;
// 用实际容器宽度(containerWidthNum, 随最大按钮自适应)做中心对齐,
// 按钮调大后容器变宽时仍与 Top 按钮保持中心对齐
const offset = this.layoutTopRight + this.layoutTopSize / 2 - this.containerWidthNum / 2;
return this.rpxStr(offset);
},
},
watch: {
@@ -571,6 +634,23 @@ export default {
// 关键: 手动同步当前 themeColor(覆盖 watch immediate 失效的场景)
// 详见上面的注释。_applyThemeColor 内部已判 $el 存在性,所有平台都安全。
this._applyThemeColor(this.$store && this.$store.state && this.$store.state.themeColor);
// 公告栏避让: 测量视口 + 公告栏(diy-notice)位置, 把悬浮按钮放到其正下方
this.updateViewport();
this.measureNotice();
// 延迟复测: 页面 DIY 内容(含 diy-notice)可能晚于本组件挂载后才渲染
this._noticeTimers = [
setTimeout(() => this.measureNotice(), 300),
setTimeout(() => this.measureNotice(), 800),
];
// #ifdef H5
// 不再监听 scroll: containerBottom 已改用「文档坐标」(视口坐标 + 滚动距离)计算,
// 得到与滚动无关的恒定 bottom —— 按钮固定在"页面顶部时公告栏正下方",
// 滚动时按钮静止、公告栏自行滚走, 不再来回滑动。
// 仅监听 resize(旋转/尺寸变化), 让按钮在视口尺寸变化时重新避让一次。
this._scrollHandler = this._onScroll.bind(this);
window.addEventListener('resize', this._scrollHandler);
// #endif
},
beforeDestroy() {
// H5 Teleport 还原:把元素从 body 移回原父节点,避免内存泄漏
@@ -579,9 +659,158 @@ export default {
this._origParent.appendChild(this.$el);
this._origParent = null;
}
// 清理公告栏避让的滚动/缩放监听与定时器
if (this._scrollHandler) {
window.removeEventListener('scroll', this._scrollHandler);
window.removeEventListener('resize', this._scrollHandler);
this._scrollHandler = null;
}
if (this._noticeTimers) {
this._noticeTimers.forEach((t) => clearTimeout(t));
this._noticeTimers = null;
}
if (this._scrollRAF) {
cancelAnimationFrame(this._scrollRAF);
this._scrollRAF = null;
}
// #endif
},
methods: {
// ============================================================
// rpx 换算工具(内联样式单位跨端兼容的关键)
// ------------------------------------------------------------
// 问题: 动态 :style 绑定里的 rpx, 微信小程序原生支持,
// 但 vue2 uni-app 的 H5 端不做编译转换 —— 浏览器不认识 rpx,
// 整条内联声明被当作非法值忽略, 回落到旧 CSS(容器 100rpx),
// 这就是"小程序正常、H5 大按钮右侧被裁"的根因。
// 解决: H5 端所有内联尺寸一律用 upx2px 换算成 px 输出;
// 小程序端保持 rpx 原样输出。
// ============================================================
// #ifdef H5
rpxNum(n) {
const n2 = Number(n) || 0;
try {
const w = (typeof window !== 'undefined' && window.innerWidth) || 375;
return (n2 * w) / 750;
} catch (e) {
return n2 / 2; // window 异常时按 375px 视口兜底
}
},
rpxStr(n) {
return this.rpxNum(n) + 'px';
},
// #endif
// #ifndef H5
rpxNum(n) {
return Number(n) || 0;
},
rpxStr(n) {
return (Number(n) || 0) + 'rpx';
},
// #endif
// ============================================================
// 公告栏(diy-notice 跑马灯)实时测量: 让悬浮按钮避让到其正下方
// ------------------------------------------------------------
// 公告栏是页面流/固定底部的 DIY 组件(diy-notice), 高度与位置动态,
// 无法用固定常量避让。这里用 uni 选择器读取其视口坐标(px),
// containerBottom 据此把按钮放到公告栏底边之下。
// 滚动/缩放时公告栏视口坐标会变化, 故监听 scroll/resize 重新测量。
// ============================================================
// 更新视口尺寸(换算 rpx 用)
updateViewport() {
try {
if (typeof window !== 'undefined' && window.innerWidth) {
this.winW = window.innerWidth;
this.winH = window.innerHeight;
} else {
const info = uni.getSystemInfoSync();
this.winW = info.windowWidth || 375;
this.winH = info.windowHeight || 667;
}
} catch (e) {
this.winW = this.winW || 375;
this.winH = this.winH || 667;
}
},
// 测量 .diy-notice 的视口坐标(无公告栏时置空, 走基础定位)
measureNotice() {
try {
const q = uni.createSelectorQuery();
q.select('.diy-notice').boundingClientRect((rect) => {
if (rect && rect.height > 0) {
this.noticeRect = {
top: rect.top,
bottom: rect.bottom,
height: rect.height,
};
} else {
this.noticeRect = null; // 无公告栏 → 基础定位
}
}).exec();
} catch (e) {
this.noticeRect = null;
}
},
// #ifdef H5
// H5: 滚动/缩放用 rAF 节流重新测量, 让按钮始终跟随公告栏
_onScroll() {
if (this._scrollRAF) return;
this._scrollRAF = requestAnimationFrame(() => {
this._scrollRAF = null;
this.updateViewport();
this.measureNotice();
});
},
// #endif
// 读取逐按钮尺寸 token(rpx 数值):
// 优先 hover_nav_{type}_btn_size, 其次 hover_nav_{type}_size, 都未配置回退 72
// 数据源: store.state.themeStyle(响应式, 后台覆写 merge 后即生效)
// 兼容值格式: 97(数字) / '97rpx' / '97', 非法或 <=0 一律回退 72
btnSizeRpx(type) {
let theme = null;
try {
theme = (this.$store && this.$store.state) ? this.$store.state.themeStyle : null;
} catch (e) { theme = null; }
const keys = ['hover_nav_' + type + '_btn_size', 'hover_nav_' + type + '_size'];
if (theme && typeof theme === 'object') {
for (let i = 0; i < keys.length; i++) {
const raw = theme[keys[i]];
if (raw === undefined || raw === null || raw === '') continue;
const n = parseFloat(raw);
if (Number.isFinite(n) && n > 0) return n;
}
}
return 72;
},
// .btn-item 的 inline-style 锁定(按按钮类型取尺寸, 见 btnSizeRpx):
// inline-style 优先级高于 CSS class, 锁死尺寸 + 正圆, 防止被 flex 布局压缩成椭圆
btnItemStyle(type) {
const s = this.rpxStr(this.btnSizeRpx(type));
return {
width: s,
height: s,
'min-width': s,
'min-height': s,
'max-width': s,
'max-height': s,
// 内部图标(.iconfont/.icox)通过该变量跟随按钮尺寸:
// 图标盒子里原本锁死 72rpx, 按钮调大后图标仍 72rpx,
// 又因列 flex 横轴默认贴左 → 图标偏在按钮左上角
'--btn-size': s,
'aspect-ratio': '1',
// border-radius 保留作 clip-path 不支持时的 fallback
'border-radius': '50%',
'flex-shrink': '0',
'flex-grow': '0',
'align-self': 'center',
'box-sizing': 'border-box',
padding: '0',
margin: this.rpxStr(14) + ' 0',
overflow: 'hidden',
};
},
// 刷新当前路由与页面栈深度(供 fbVisible 的页面范围判定 / pageCount 老判定)
refreshRoute() {
this.currentRoute = getCurrentRoute();
@@ -598,9 +827,13 @@ export default {
if (typeof document === 'undefined') return; // SSR/非浏览器环境兜底
const root = document.documentElement;
const computed = getComputedStyle(root);
// CSS 变量在 H5 编译后是 px;组件内部统一按 750 设计稿 rpx 值计算,
// 输出时再经 rpxStr() 换算回 px,避免 px/rpx 混算导致尺寸/位置错乱
const scale = ((typeof window !== 'undefined' && window.innerWidth) || 375) / 750;
const getNum = (name, fallback) => {
const v = parseFloat(computed.getPropertyValue(name));
return Number.isFinite(v) ? v : fallback;
if (!Number.isFinite(v) || scale <= 0) return fallback;
return v / scale; // px → 设计稿 rpx 值
};
this.layoutTopRight = getNum('--top-btn-right', 46);
this.layoutTopBottom = getNum('--top-btn-bottom', 272);
@@ -885,8 +1118,13 @@ export default {
* 保证容器的实际宽度与 JS 计算用到的宽度始终一致。 */
width: var(--floating-btn-width, 100rpx);
box-sizing: border-box;
transition: 0.3s;
overflow: hidden;
/* 去掉过渡动画: 切换页面重挂载时 bottom/width/right 变化会触发滑动,
* 造成"突然移动"的观感; 位置用缓存保证恒定, 无需动画 */
/* 关键: 不裁剪子元素。按钮尺寸由后台 token 任意调节(hover_nav_*_btn_size 可远超容器宽度),
* 且 rpx→px 取整存在亚像素误差, overflow:hidden 会把按钮右侧/四角切掉一条(变形元凶)。
* 按钮自身已有 border-radius:50% + overflow:hidden 自裁剪, 背景图圆角由本元素
* border-radius 保证(背景不受 overflow 影响), 故这里必须放开为 visible。 */
overflow: visible;
/* 与 to-top.vue 的 .mescroll-totop 一致,适配 iPhoneX 等安全区 */
margin-bottom: var(--window-bottom);
}
@@ -894,6 +1132,9 @@ export default {
.btn-item {
display: flex;
justify-content: center;
/* 横向居中: 列布局下横轴是 align-items, 固定宽度的子元素
* (如锁死尺寸的 .iconfont 图标盒)默认贴左, 必须显式居中 */
align-items: center;
text-align: center;
flex-direction: column;
line-height: 1;
@@ -928,22 +1169,42 @@ export default {
background-color: var(--hover-nav-bg-color);
}
/* 逐按钮背景/文字颜色覆写(与后台 9 个 key 对应, 未配置时回退全局 --hover-nav-*):
* hover_nav_lang_bg_color / hover_nav_lang_text_color → --hover-nav-lang-bg-color / --hover-nav-lang-text-color
* hover_nav_kefu_bg_color / hover_nav_kefu_text_color → --hover-nav-kefu-bg-color / --hover-nav-kefu-text-color
* hover_nav_phone_bg_color / hover_nav_phone_text_color → --hover-nav-phone-bg-color / --hover-nav-phone-text-color
* 文字色经 .btn-item 的 color 继承给内部 text/图标(.lang-btn-text 为 color: inherit) */
.btn-lang {
background-color: var(--hover-nav-lang-bg-color, var(--hover-nav-bg-color));
color: var(--hover-nav-lang-text-color, var(--hover-nav-text-color));
}
.btn-kefu {
background-color: var(--hover-nav-kefu-bg-color, var(--hover-nav-bg-color));
color: var(--hover-nav-kefu-text-color, var(--hover-nav-text-color));
}
.btn-phone {
background-color: var(--hover-nav-phone-bg-color, var(--hover-nav-bg-color));
color: var(--hover-nav-phone-text-color, var(--hover-nav-text-color));
}
.btn-item text {
font-size: 28rpx;
/* 悬浮按钮内文字/图标字号(后台 hover_nav_font_size 可调, 默认与图标 36rpx 对齐) */
font-size: var(--hover-nav-font-size, 36rpx);
}
.iconfont,
.icox {
font-size: 36rpx;
/* 悬浮按钮内图标字号(后台 hover_nav_font_size 可调) */
font-size: var(--hover-nav-font-size, 36rpx);
font-weight: bold;
display: flex;
justify-content: center;
align-items: center;
/* 不再设 width: 100% / height: 100% 再覆盖为 72rpx 的写法,
* 微信小程序/H5 对 width: 100% 在 flex 列布局里的高度计算有差异,
* 直接固定 72x72 更稳。 */
width: 72rpx;
height: 72rpx;
/* 尺寸跟随所在按钮: 按钮内联样式写入 --btn-size(=按钮实际尺寸),
* 图标盒不再锁死 72rpx —— 否则按钮调大后图标偏小且贴左上。
* 72rpx 兜底 = 按钮未走 btnItemStyle 内联样式时的默认尺寸。 */
width: var(--btn-size, 72rpx);
height: var(--btn-size, 72rpx);
margin: 0;
border-radius: 50%;
padding: 0;
@@ -961,9 +1222,17 @@ export default {
0 -1rpx 0 rgba(0, 0, 0, 0.18);
}
/* 逐按钮字号覆写: 后台 hover_nav_phone/kefu_font_size 可调, 未设时回退全局 --hover-nav-font-size */
.iconfont.icon-dianhua {
font-size: var(--hover-nav-phone-font-size, var(--hover-nav-font-size, 36rpx));
}
.icox.icox-kefu {
font-size: var(--hover-nav-kefu-font-size, var(--hover-nav-font-size, 36rpx));
}
.iconfont text,
.icox text {
font-size: 36rpx;
font-size: var(--hover-nav-font-size, 36rpx);
font-weight: bold;
}
@@ -975,7 +1244,8 @@ export default {
}
.ai-icon {
font-size: 40rpx;
/* emoji 客服图标: 基准字号用 hover_nav_kefu_font_size(回退全局), 再 ×1.11(原 40/36) */
font-size: calc(var(--hover-nav-kefu-font-size, var(--hover-nav-font-size, 36rpx)) * 1.11);
width: 100%;
height: 100%;
display: flex;
@@ -994,7 +1264,8 @@ export default {
justify-content: center;
width: 100%;
height: 100%;
font-size: 24rpx;
/* 语言短码文字: 基准字号用 hover_nav_lang_font_size(回退全局 hover_nav_font_size), 文字实际按 0.667 缩放 */
font-size: calc(var(--hover-nav-lang-font-size, var(--hover-nav-font-size, 36rpx)) * 0.667);
line-height: 1;
font-weight: 600;
letter-spacing: 0;

View File

@@ -0,0 +1,247 @@
<template>
<!--
自绘导航栏:把原生导航栏左侧的 "<" 换成 "‹ 返回" 文字
背景:微信小程序原生导航栏的返回按钮是客户端系统控件,pages.json 的任何配置、
官方 <navigation-bar> 组件(只支持 title / front-color / background-color / loading)
都无法修改它的内容。要显示"返回"二字,只能关闭原生栏后自绘。
使用前提:
1. 该页面在 pages.json 中开启 "navigationStyle": "custom"(组件只负责渲染,不自动改配置)
2. 该页面不能是 web-view 页面 —— 官方明确 "navigationStyle: custom 对 web-view 组件无效",
且 web-view 会铺满整页覆盖其他组件,自绘的导航栏不会显示
布局:组件是普通流式节点(非 fixed),放在页面顶部即可把内容自然下推。
-->
<view
v-if="visible"
class="ns-mp-navbar"
:class="{ 'is-fixed': fixed }"
:style="{ background: bgColor, paddingTop: statusBarHeight + 'px' }"
>
<view class="ns-mp-navbar__inner" :style="{ height: navBarHeight + 'px' }">
<view class="ns-mp-navbar__side">
<view
v-if="showBack && canBack"
class="ns-mp-navbar__back"
hover-class="ns-mp-navbar__back--hover"
hover-stay-time="80"
@tap="onBack"
>
<text class="iconfont icon-back_light ns-mp-navbar__arrow" :style="{ color }"></text>
<text class="ns-mp-navbar__text" :style="{ color }">{{ backText }}</text>
</view>
<slot name="left"></slot>
</view>
<view class="ns-mp-navbar__title" :style="{ color }">{{ title }}</view>
<view class="ns-mp-navbar__side ns-mp-navbar__side--right">
<slot name="right"></slot>
</view>
</view>
</view>
</template>
<script>
// 状态栏 / 胶囊信息:用于算出与原生导航栏一致的布局高度
let systemInfo = {};
let menuButtonInfo = { top: 0, height: 32, right: 0, width: 0 };
try {
systemInfo = uni.getSystemInfoSync() || {};
} catch (e) {
systemInfo = {};
}
// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ || MP-HARMONY
try {
menuButtonInfo = uni.getMenuButtonBoundingClientRect() || menuButtonInfo;
} catch (e) {}
// #endif
export default {
name: 'ns-mp-navbar',
props: {
// 中间标题
title: {
type: String,
default: ''
},
// 导航栏背景色
bgColor: {
type: String,
default: '#ffffff'
},
// 文字 / 图标颜色
color: {
type: String,
default: '#000000'
},
// 返回按钮文字(原生导航栏只能显示 "<",这里可自定义)
backText: {
type: String,
default: '返回'
},
// 是否显示返回按钮
showBack: {
type: Boolean,
default: true
},
// 是否悬浮在页面之上(沉浸式页面用;false 时占文档流,会把内容往下推)
fixed: {
type: Boolean,
default: false
},
// 无页面栈时(如分享直接进入)跳转的首页地址
homePath: {
type: String,
default: '/pages/index/index'
},
// 自定义返回逻辑
customBack: {
type: Function,
default: null
},
// H5 端是否渲染(H5 由 uni-app 自带头像栏,默认不渲染,避免双导航栏)
showOnH5: {
type: Boolean,
default: false
}
},
data() {
return {
statusBarHeight: systemInfo.statusBarHeight || 20,
navBarHeight: 44,
visible: true,
// 页面栈里是否还有上级页面(无上级页面时原生导航栏也不显示返回键)
canBack: true
};
},
computed: {
// 导航栏总高度(状态栏 + 内容区),页面如需自行占位可取该值
navbarHeight() {
return this.statusBarHeight + this.navBarHeight;
}
},
created() {
// 导航栏内容区高度:MP 端按胶囊位置推算,与原生导航栏保持一致;其余端用 44
// #ifdef MP
const statusBarHeight = this.statusBarHeight;
const h = (menuButtonInfo.top - statusBarHeight) * 2 + menuButtonInfo.height;
// 兜底:胶囊信息异常时退回 44
this.navBarHeight = h > 0 ? h : 44;
// #endif
// #ifdef H5
this.visible = this.showOnH5;
// #endif
},
mounted() {
// 页面栈只有一页(分享/扫码直达)时,原生导航栏也无返回键,这里保持一致
const pages = (typeof getCurrentPages === 'function' && getCurrentPages()) || [];
this.canBack = pages.length > 1;
// 把实际总高度抛给页面,便于页面修正内容区高度,避免多出一屏空白
this.$emit('ready', this.statusBarHeight + this.navBarHeight);
},
methods: {
onBack() {
if (typeof this.customBack === 'function') {
this.customBack();
return;
}
const pages = (typeof getCurrentPages === 'function' && getCurrentPages()) || [];
if (pages.length > 1) {
uni.navigateBack();
return;
}
// 顶层页面(分享 / 扫码直接进入):回首页
uni.switchTab({
url: this.homePath,
fail: () => {
uni.reLaunch({ url: this.homePath });
}
});
}
}
};
</script>
<style scoped lang="scss">
.ns-mp-navbar {
width: 100%;
box-sizing: border-box;
}
.ns-mp-navbar.is-fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 990;
}
.ns-mp-navbar__inner {
position: relative;
display: flex;
align-items: center;
width: 100%;
box-sizing: border-box;
}
.ns-mp-navbar__side {
position: relative;
z-index: 1;
display: flex;
align-items: center;
height: 100%;
min-width: 160rpx;
padding-left: 20rpx;
box-sizing: border-box;
}
.ns-mp-navbar__side--right {
justify-content: flex-end;
padding-left: 0;
padding-right: 20rpx;
}
.ns-mp-navbar__back {
display: flex;
align-items: center;
padding: 10rpx 20rpx 10rpx 0;
}
.ns-mp-navbar__back--hover {
opacity: 0.5;
}
.ns-mp-navbar__arrow {
font-size: 34rpx;
line-height: 1;
}
.ns-mp-navbar__text {
margin-left: 2rpx;
font-size: 30rpx;
line-height: 1;
}
.ns-mp-navbar__title {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
display: flex;
align-items: center;
justify-content: center;
padding: 0 160rpx;
font-size: 32rpx;
line-height: 1.2;
text-align: center;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>

View File

@@ -53,7 +53,7 @@
<ns-copyright v-show="isShowCopyRight" />
</view>
<template v-if="adv.advshow != -1">
<template v-if="adv && adv.advshow != -1">
<view @touchmove.prevent.stop>
<uni-popup ref="uniPopupWindow" type="center" class="wap-floating" :maskClick="false">
<view class="small-bot">