微信/支付寶小程序實現彈窗動畫縮放到某個位置的示例代碼
HTML
<view wx:if="{{advertiseFlag}}" class="advertise-wrapper" style="background-color:{{transitionData.statusBtn == 'playing'?'rgba(255,255,255,0)':''}}" bindtap="jumpFn"> <view class="advertise-box" style="width:{{transitionData.width}};height:{{transitionData.height}};left:{{transitionData.left}};top:{{transitionData.top}};opacity:{{transitionData.opacity}};animation:{{transitionData.animation}}"> <image data-status="{{transitionData.statusBtn}}" catchtap="handleJumpValue" src="{{ advertiseMsg.url || 'https://yizhen-mamapai-dev.oss-cn-zhangjiakou.aliyuncs.com/certification/2024-06-13/b1791b525e974c0aae8a0c82a8410a9b.png'}}"> </image> <view class="jump-box" catchtap="jumpFn" data-status="{{transitionData.statusBtn}}"> 跳過{{defaultTime?defaultTime:''}} </view> </view> </view>
CSS
.advertise-wrapper { width: 100%; height: 100vh; background: rgba(0, 0, 0, 0.75); position: fixed; top: 0; left: 0; z-index: 999; display: flex; justify-content: center; align-items: center; } .advertise-box { width: 580rpx; height: 980rpx; position: absolute; transition: all 1s linear; } @keyframes shrinkAndMoveToPosition { from { transform: scale(1); opacity: 1; } to { transform: scale(0.5); opacity: 0; } } .advertise-box image { width: 100%; height: 100%; } .jump-box { background: rgba(0, 0, 0, 0.8); border-radius: 10px; padding: 4rpx 16rpx; position: absolute; top: 20rpx; right: 20rpx; color: #fff; font-size: 12px; }
JS
動畫函數
options的參數
from : 起始值 比如:0
to : 結束值 比如:100
totalMS :變化總時間 比如: 1000
duration : 每多少秒變化的次數 比如: 1
onmove :開始移動的回調函數
onend :移動結束的回調函數
let timer; function createAnimation(option) { // 起始值、結束值、變化總時間 var { from, to, totalMS, duration, onmove, onend } = option; totalMS = totalMS || 1000; duration = duration || 10; // 每多少時間變化一次 var times = Math.floor(totalMS / duration); // 變化的次數 var dis = (to - from) / times; // 每次變化的量 var curTimes = 0; // 每次變化的函數 var timer = setInterval(() => { from += dis; curTimes++; // 變化完成,這里保證onmove 在 onend以前執(zhí)行 if (curTimes >= times) { from = to; onmove && onmove(from); onend && onend(); clearInterval(timer); return; } onmove && onmove(from); }, duration); }
獲取dom
我們點擊跳轉的時候,首先需要獲取到當前點擊 dom 的 status,如果當前的狀態(tài)為 playing 直接 return,否則開始獲取當前的 dom 信息,找到當前點擊的 dom 和所要跳轉到的 dom 所在位置,然后找到所要跳轉的位置后,把當前點擊的dom和所要去的dom傳給開始的動畫函數
handleGetDom(type) { if (!type || type <= 0) return let _this = this wx.createSelectorQuery().select('.advertise-box').boundingClientRect() .selectAll('.grid-container .item').boundingClientRect().exec((ret) => { const [popRect, endDoms] = ret; const targetIndex = endDoms.findIndex((item) => item.id == type); if (targetIndex === -1) return; const endDom = endDoms[targetIndex]; _this.startTransition(popRect, endDom); }) },
開始動畫過渡
根據獲取 dom 和所要去的 dom 的位置,在拿到要結束 dom 之前先把 status 狀態(tài)設置為 playing ,這樣后我們就可以設置動畫效果然后把對應的參數傳給動畫函數 createAnimation 。
// 開始動畫過渡 startTransition(popRect, endDom) { const _this = this; // 設置點擊狀態(tài)為playing _this.setData({ transitionData: { ..._this.data.transitionData, statusBtn: 'playing' } }); const centerX = endDom.left const centerY = endDom.top _this.setData({ transitionData: { ..._this.data.transitionData, animation: "shrinkAndMoveToPosition 2s forwards" } }); createAnimation({ from: popRect.left, to: centerX, totalMS: 1000, onmove: (n) => { _this.updateTransitionData(endDom, centerX, centerY); }, onend: () => { _this.endTransition(endDom); } }); },
動畫的更新函數
這個地方需要注意的是在支付寶中 left、top 不用需要加 px,width和height自行決定用不用除以2
// 更新動畫過程中的數據 updateTransitionData(endDom, centerX, centerY) { this.setData({ transitionData: { ...this.data.transitionData, width: `${endDom.width / 2}px`, height: `${endDom.height / 2}px`, left: `${centerX}px`, top: `${centerY}px` } }); },
動畫的結束函數
在動畫結束的時候我們需要把 status 更改為 end , opacity 設置為 0,清除定時器就可以了
// 結束動畫并處理跳轉 endTransition(endDom) { const _this = this; wx.showTabBar(); _this.setData({ transitionData: { ..._this.data.transitionData, statusBtn: 'end', opacity: 0 }, advertiseFlag: false }); clearInterval(timer); const currItem = { ...endDom.dataset.item, richTextType: 2, appletAdvertisementId: endDom.dataset.item.type } _this.handleJumpTypePage(currItem); },
動畫所有相關的事件函數
// 跳轉類型 handleJumpValue(e) { let { relationHomeSwitch, relationHomeType, id } = this.data.advertisingPopup this.handleClickDataSave(id) if (relationHomeType && relationHomeSwitch == 1) { let status = e.currentTarget.dataset.status // 判斷是否有點擊過 statusBtn if (status == 'playing') return; this.handleGetDom(relationHomeType) } else if (relationHomeSwitch == 2) { let data = { ...this.data.advertisingPopup, richTextType: 3, } this.handleJumpTypePage(data) } else { wx.showTabBar(); this.setData({ advertiseFlag: false }); clearInterval(timer); } }, // 獲取dom handleGetDom(type) { if (!type || type <= 0) return let _this = this wx.createSelectorQuery().select('.advertise-box').boundingClientRect() .selectAll('.grid-container .item').boundingClientRect().exec((ret) => { const [popRect, endDoms] = ret; const targetIndex = endDoms.findIndex((item) => item.id == type); if (targetIndex === -1) return; const endDom = endDoms[targetIndex]; _this.startTransition(popRect, endDom); }) }, // 開始動畫過渡 startTransition(popRect, endDom) { const _this = this; // 設置點擊狀態(tài)為playing _this.setData({ transitionData: { ..._this.data.transitionData, statusBtn: 'playing' } }); const centerX = endDom.left const centerY = endDom.top _this.setData({ transitionData: { ..._this.data.transitionData, animation: "shrinkAndMoveToPosition 2s forwards" } }); createAnimation({ from: popRect.left, to: centerX, totalMS: 1000, onmove: (n) => { _this.updateTransitionData(endDom, centerX, centerY); }, onend: () => { _this.endTransition(endDom); } }); }, // 更新動畫過程中的數據 updateTransitionData(endDom, centerX, centerY) { this.setData({ transitionData: { ...this.data.transitionData, width: `${endDom.width / 2}px`, height: `${endDom.height / 2}px`, left: `${centerX}px`, top: `${centerY}px` } }); }, // 結束動畫并處理跳轉 endTransition(endDom) { const _this = this; wx.showTabBar(); _this.setData({ transitionData: { ..._this.data.transitionData, statusBtn: 'end', opacity: 0 }, advertiseFlag: false }); clearInterval(timer); const currItem = { ...endDom.dataset.item, richTextType: 2, appletAdvertisementId: endDom.dataset.item.type } _this.handleJumpTypePage(currItem); }, // 點擊 handleHomeConfigClick(id) { let params = { id: id } api.post('/main-service/home-config/click', params).then((res) => { if (res.code == 1) { console.log(res, 'res'); } }).catch((err) => { console.log(err, 'err'); }) }, jumpFn() { wx.showTabBar(); this.setData({ advertiseFlag: false }); clearInterval(timer); }, // 動畫end
完整實現代碼
// pages/prize/prize.js const api = require('../../common/api') const App = getApp() const getAuthCode = require('../../common/authen.js').getAuthCode let timer; let count = 0; function createAnimation(option) { // 起始值、結束值、變化總時間 var { from, to, totalMS, duration, onmove, onend } = option; totalMS = totalMS || 1000; duration = duration || 10; // 沒多少時間變化一次 var times = Math.floor(totalMS / duration); // 變化的次數 var dis = (to - from) / times; // 每次變化的量 var curTimes = 0; // 每次變化的函數 var timer = setInterval(() => { from += dis; curTimes++; // 變化完成,這里保證onmove 在 onend以前執(zhí)行 if (curTimes >= times) { from = to; onmove && onmove(from); onend && onend(); clearInterval(timer); return; } onmove && onmove(from); }, duration); } Page({ data: { transitionData: { statusBtn: '', // 是否已經點擊過 left: '', top: '', width: '580rpx', height: '980rpx', opacity: 1 }, marketingId: "", // 營銷id styleConfigData: {}, imgSrc: [], paramStr: '', indicatorDots: false, autoplay: true, vertical: false, interval: 2000, circular: true, duration: 1500, defaultTime: 4, //默認時間 advertiseFlag: false, advertiseMsg: {}, activityData: { sourceType: '' }, styleHomeImage: {}, activeIndex: "", // 切換下標 interval: 3000, advertisingRotation: [], // 廣告位輪播 newHomepage: [], }, /** * 生命周期函數--監(jiān)聽頁面加載 */ onLoad: function (options) { // this.getImage() // this.getStyleConfig() this.getAuth() this.getHomeConfigPage() this.handleGetAxiosData() this.getAdvertisement() }, onShow() { let token = wx.getStorageSync('token') if (App.globalData.activityData.sourceType == 'activity' && App.globalData.inviteCustomerNum < 2 && token) { this.handleActivity() } }, handleActivity() { const params = App.globalData.activityData api.post('/main-service/customer-invite-record', params).then((res) => { if (res.code === 1) { console.log('邀請?zhí)幚沓晒?) App.globalData.inviteCustomerNum = 2 } if (res.code == 1010002) { console.log('邀請?zhí)幚硎?) App.globalData.inviteCustomerNum = 1 } }) }, // 獲取首頁頭部配置 getHomeConfigPage() { api.get("/main-service/home-config/list").then((res) => { if (res.code == 1) { let originalHomepage = res.data && res.data.sort((a, b) => { return a.type - b.type }) || [] // 處理數據,添加額外屬性用于渲染 const processedHomepage = originalHomepage.map(item => { return { ...item, shouldDisplay: this.shouldDisplayItem(item), className: this.getClassByType(item.type), imageMode: this.getImageMode(item.type), showMenu: item.type >= 5, defaultImage: this.getDefaultImage(item.type) }; }); this.setData({ newHomepage: processedHomepage }) } }).catch((err) => { console.log(err, 'err'); }) }, // 獲取頁面樣式配置 getStyleConfig() { api.get('/main-service/activity_style_config').then((res) => { if (res.code === 1) { const { data } = res this.setData({ styleConfigData: { ...data, topImg: res.data.imgUrl.split(",")[0], bottomImg: res.data.imgUrl.split(",")[1], } }) } }) }, //數據 handleGetAxiosData() { let params = { type: 39 } api.get(`/main-service/sys/info`, params).then((res) => { console.log(res, 'res') if (res.code == 1) { this.setData({ styleHomeImage: res.data.remark ? JSON.parse(res.data.remark) : {}, }) } }) }, getImage() { api.get('/main-service/home-page/advertising').then(res => { this.setData({ imgSrc: res.data.weChatBackgroundUrl }) }) }, // 獲取 廣告位輪播圖 getAdvertisement() { const params = { position: 1 } api.get('/main-service/advertisement', params).then((res) => { if (res.code == 1) { this.setData({ advertisingRotation: res.data }) } }) }, // 改變圖片 changeImg(e) { this.activeIndex = e.detail.current this.setData({ activeIndex: e.detail.current }) }, getAuth() { getAuthCode().then(res => { let authCode = res.authCode; let params = { code: authCode }; this.getAdvertiseMsg(params); }); }, //獲取彈窗廣告信息 getAdvertiseMsg(params) { api.get("/main-service/applet-advertisement/v2", params).then(res => { if (res.code == 1) { this.setData({ advertiseFlag: res.data.status == 1 ? true : false, advertiseMsg: res.data, advertisingPopup: { ...res.data } }); if (res.data.id) { wx.hideTabBar(); } if (res.data.status == 1) { timer = setInterval(() => { if (this.data.defaultTime > 0) { let time = (this.data.defaultTime -= 1); this.setData({ defaultTime: time }); return; } if (!this.data.defaultTime) { clearInterval(timer); this.isLike(); } }, 1000); } } }); }, //是否感興趣 isLike() { let id = this.data.advertiseMsg.id; if (id) { api.get(`/main-service/applet-advertisement/${id}`).then(res => { if (res.code == 1) { console.log("感興趣"); } }); } }, // 跳轉詳情 handleJumpDetails(item) { let { id, jumpType } = item.currentTarget.dataset.value if (jumpType == 13) { wx.navigateTo({ url: `/addressManagement/pages/richText/richText?jumpId=${id}` }); } }, // 頁面跳轉 handleJumpToPage(e) { let { item } = e.currentTarget.dataset this.handleHomeConfigClick(item.id) wx.hideLoading() let data = { ...item, richTextType: 2, appletAdvertisementId: item.type } wx.hideLoading() this.handleJumpTypePage(data) }, // 根據跳轉類型處理頁面跳轉 handleJumpTypePage(item) { const jumpType = Number(item.jumpType); this.jumpFn() const routes = { 1: () => this.handlePageTo(), 2: () => wx.navigateTo({ url: "/addressManagement/pages/invitingWithCourtesy/invitingWithCourtesy" }), 3: () => wx.navigateTo({ url: `/addressManagement/pages/invitationGiftDetail/invitationGiftDetail?id=${item.jumpValue}` }), 4: () => wx.switchTab({ url: '/pages/activity/activity' }), 5: () => wx.navigateTo({ url: `/pages/activityDetail/activityDetail?activityId=${item.jumpValue}` }), 6: () => wx.navigateTo({ url: `/addressManagement/pages/richText/richText?jumpId=${item.appletAdvertisementId}&type=${item.richTextType}` }), // 7: () => wx.navigateTo({ url: `/pages/content-detail/content-detail?id=${item.jumpValue}&type=1` }), // 8: () => wx.navigateTo({ url: `/pages/content-detail/content-detail?id=${item.jumpValue}&type=3` }), 9: () => wx.navigateTo({ url: `/addressManagement/pages/richText/richText?jumpId=${item.appletAdvertisementId}&status=btn&type=${item.richTextType}` }), 10: () => wx.navigateTo({ url: `/addressManagement/pages/marketing/marketing?id=${item.type}&type=home` }), }; if (routes[jumpType]) { routes[jumpType](); } }, // 點擊數據 handleClickDataSave(id) { let params = { appletAdvertisementCustomerRecordId: id } api.get('/main-service/applet-advertisement/save-click-data', params).then((res) => { if (res.code == 1) { console.log(res, 'res'); } }).catch((err) => { console.log(err, 'err'); }) }, // 跳轉類型 handleJumpValue(e) { let { relationHomeSwitch, relationHomeType, id } = this.data.advertisingPopup this.handleClickDataSave(id) if (relationHomeType && relationHomeSwitch == 1) { let status = e.currentTarget.dataset.status // 判斷是否有點擊過 statusBtn if (status == 'playing') return; this.handleGetDom(relationHomeType) } else if (relationHomeSwitch == 2) { let data = { ...this.data.advertisingPopup, richTextType: 3, } this.handleJumpTypePage(data) } else { wx.showTabBar(); this.setData({ advertiseFlag: false }); clearInterval(timer); } }, // 獲取dom handleGetDom(type) { if (!type || type <= 0) return let _this = this wx.createSelectorQuery().select('.advertise-box').boundingClientRect() .selectAll('.grid-container .item').boundingClientRect().exec((ret) => { const [popRect, endDoms] = ret; const targetIndex = endDoms.findIndex((item) => item.id == type); if (targetIndex === -1) return; const endDom = endDoms[targetIndex]; _this.startTransition(popRect, endDom); }) }, // 開始動畫過渡 startTransition(popRect, endDom) { const _this = this; // 設置點擊狀態(tài)為playing _this.setData({ transitionData: { ..._this.data.transitionData, statusBtn: 'playing' } }); const centerX = endDom.left const centerY = endDom.top _this.setData({ transitionData: { ..._this.data.transitionData, animation: "shrinkAndMoveToPosition 2s forwards" } }); createAnimation({ from: popRect.left, to: centerX, totalMS: 1000, onmove: (n) => { _this.updateTransitionData(endDom, centerX, centerY); }, onend: () => { _this.endTransition(endDom); } }); }, // 更新動畫過程中的數據 updateTransitionData(endDom, centerX, centerY) { this.setData({ transitionData: { ...this.data.transitionData, width: `${endDom.width / 2}px`, height: `${endDom.height / 2}px`, left: `${centerX}px`, top: `${centerY}px` } }); }, // 結束動畫并處理跳轉 endTransition(endDom) { const _this = this; wx.showTabBar(); _this.setData({ transitionData: { ..._this.data.transitionData, statusBtn: 'end', opacity: 0 }, advertiseFlag: false }); clearInterval(timer); const currItem = { ...endDom.dataset.item, richTextType: 2, appletAdvertisementId: endDom.dataset.item.type } _this.handleJumpTypePage(currItem); }, // 點擊 handleHomeConfigClick(id) { let params = { id: id } api.post('/main-service/home-config/click', params).then((res) => { if (res.code == 1) { console.log(res, 'res'); } }).catch((err) => { console.log(err, 'err'); }) }, jumpFn() { wx.showTabBar(); this.setData({ advertiseFlag: false }); clearInterval(timer); }, // 動畫end handlePageTo: function () { let that = this wx.showLoading({ title: '加載中', mask: true }) this.checkAttestation() // that.getUserInfo() }, // getUserInfo() { // let that = this // getAuthCode().then((res) => { // const { // authCode // } = res // let params = { // loginType: 7, // isRelatedPhoneNumber: 0, // grantCode: authCode // } // api.post('/main-service/customer/login', params).then(({ // data // }) => { // const { // isRelatedPhoneNumber, // phoneNumber, // token // } = data // if (isRelatedPhoneNumber == 0) { // wx.hideLoading() // wx.reLaunch({ // url: '/pages/login/login?sourceType=prize' // }); // return // } // if (isRelatedPhoneNumber == 1) { // wx.hideLoading() // wx.setStorageSync('token', token) // that.checkAttestation() // return // } // }) // }) // }, checkAttestation() { api.get('/main-service/pregnant-certification/status').then(({ data }) => { wx.hideLoading() const { isWhite, isSellOut, status, identityType, isSyncTaoBao } = data if (isWhite == 0) { if (status == 0) { // 跳轉認證頁面 wx.navigateTo({ url: '/pages/authentication/authentication' }) } if (status == 1) { // 跳轉認證中 wx.navigateTo({ url: '/pages/AddCustomer/AddCustomer' }) } if (status == 2) { // 打開領取鏈接 if (isSellOut) { // 禮品售罄 // "identityType": 1:孕媽 2:寶媽 if (!isSyncTaoBao) { wx.navigateTo({ url: '/pages/sellOut/sellOut' }) // if (identityType == 1) { // wx.navigateTo({ // url: '/pages/sellOut/sellOut' // }) // } // if (identityType == 2) { // wx.navigateTo({ // url: `/pages/certificationPassed/certificationPassed` // }) // } } else { // 修改之后的邏輯 wx.navigateTo({ url: `/pages/giftGuide/giftGuide?status=${status}` }) } } else { wx.navigateTo({ url: `/pages/giftGuide/giftGuide?status=${status}` }) // if (identityType == 1) { // wx.navigateTo({ // url: `/pages/giftGuide/giftGuide?status=${status}` // }) // } // if (identityType == 2) { // wx.navigateTo({ // url: `/pages/certificationPassed/certificationPassed` // }) // } } } if (status == 3) { // 跳轉拒絕頁面 wx.navigateTo({ url: '/pages/certificationReject/certificationReject' }) } if (status == 4) { // 跳轉退回頁面重新編輯 wx.navigateTo({ url: `/pages/authentication/authentication?status=${status}` }) } } if (isWhite == 1) { if (isSellOut) { wx.navigateTo({ url: '/pages/sellOut/sellOut' }) } else { wx.navigateTo({ url: `/pages/giftGuide/giftGuide?status=${status}` }) } } }) }, handleClickBanner() { wx.navigateTo({ url: '/addressManagement/pages/bannerDetail/bannerDetail', }) }, // 跳轉會場 handleToShare() { wx.navigateTo({ url: `/addressManagement/pages/taobaoVenue/taobaoVenue?type=home`, }); }, // 開啟分享 onShareAppMessage() {}, // 判斷是否展示該 item shouldDisplayItem(item) { if (item.type >= 5 && item.showSwitch !== 1) return false; return !!item.url || item.type <= 4; // 當 type 小于等于 4 時總是展示 }, // 根據 type 返回對應的類名 getClassByType(type) { switch (type) { case 1: return 'new-mom-gift'; case 2: return 'xhs-volunteer'; case 3: return 'douyin-volunteer'; case 4: return 'invitation-gift'; case 5: return 'advertising-space-one'; case 6: return 'advertising-space-two'; case 7: return 'advertising-space-three'; default: return ''; } }, // 根據 type 返回圖片的 mode getImageMode(type) { return type >= 5 ? 'widthFix' : 'scaleToFill'; }, // 獲取默認圖片 URL getDefaultImage(type) { return 'https://yizhen-mamapai-dev.oss-cn-zhangjiakou.aliyuncs.com/certification/2024-06-13/3cb773c6e3614c389619a24d55f868d4.png'; }, onPullDownRefresh() { Promise.all([this.getHomeConfigPage()]).then(res => { this.stopPullDownRefresh(); }); }, onUnload() { this.jumpFn() }, })
到此這篇關于微信/支付寶小程序實現彈窗動畫縮放到某個位置的文章就介紹到這了,更多相關彈窗動畫縮放到某個位置內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
bootstrap table表格插件之服務器端分頁實例代碼
Bootstrap Table是基于Bootstrap的輕量級表格插件,只需要簡單的配置就可以實現強大的支持固定表頭、單復選、排序、分頁、搜索以及自定義表頭等功能。這篇文章主要介紹了bootstrap table表格插件之服務器端分頁實例代碼,需要的朋友可以參考下2018-09-09[Bootstrap-插件使用]Jcrop+fileinput組合實現頭像上傳功能實例代碼
這篇文章主要介紹了[Bootstrap-插件使用]Jcrop+fileinput組合實現頭像上傳功能實例代碼,非常具有實用價值,需要的朋友可以參考下。2016-12-12