版权声明:本文为博主原创文章,未经博主允许不得转载。 http://blog.csdn.net/xiaoxiaoluckylucky/article/details/79374157
先上效果图:
1,先写一个js文件,toast.js
- /*jslint browser: true*/
- /*global console, Framework7, alert, Dom7*/
- /**
- * A plugin for Framework7 to show black little toasts
- *
- * @author www.timo-ernst.net
- * @license MIT
- */
- Framework7.prototype.plugins.toast = function (app, globalPluginParams) {
- 'use strict';
- var Toast = function (text, iconhtml, options) {
- var self = this,
- $$ = Dom7,
- $box;
- function hideBox($curbox) {
- if ($curbox) {
- $curbox.removeClass('fadein').transitionEnd(function () {
- $curbox.remove();
- });
- }
- }
- function isString(obj) {
- return toString.call(obj) === '[object String]';
- }
- this.show = function (message) {
- var clientLeft,
- $curbox,
- html = [];
- // Remove old toasts first if there are still any
- $$('.toast-container').off('click').off('transitionEnd').remove();
- $box = $$('<div class="toast-container show">');
- // Add content
- if (isString(iconhtml) && iconhtml.length > 0) {
- html.push(
- '<div class="toast-icon">' +
- iconhtml +
- '</div>'
- );
- }
- if (isString(message) && message.length > 0) {
- text = message;
- }
- if (isString(text) && text.length > 0) {
- html.push(
- '<div class="toast-msg">' +
- text +
- '</div>'
- );
- }
- $box.html(
- html.join('')
- );
- // Add to DOM
- clientLeft = $box[0].clientLeft;
- $$('body').append($box);
- $box.css('margin-top', $box.outerHeight() / -2 + 'px')
- .css('margin-left', $box.outerWidth() / -2 + 'px');
- // Hide box on click
- $box.click(function () {
- hideBox($box);
- });
- // Dirty hack to cause relayout xD
- clientLeft = $box[0].clientLeft;
- // Fade in toast
- $box.addClass('fadein');
- // Automatically hide box after few seconds
- $curbox = $box;
- setTimeout(function () {
- hideBox($curbox);
- }, 1500);
- };
- this.hide = function() {
- hideBox($box);
- };
- return this;
- };
- app.toast = function (text, iconhtml, options) {
- return new Toast(text, iconhtml, options);
- };
- };
2,然后在需要的地方如下使用:
- var app = new Framework7();
- var toast = app.toast('这是一个toast', '', {});
- toast.show(true);
ok。以上使用了Framework7框架,框架文档地址:http://framework7.taobao.org/docs/#.WCv_NGVZ8dU。
/***************************************** 分割线 **************************************/
2017.04.10添加:
在适配多机型的过程中,发现以上方式实现的toast在部分机型上不是水平居中,于是废弃。最终是采用插件cordova-plugin-x-toast实现了想要的效果。
插件地址:https://github.com/EddyVerbruggen/Toast-PhoneGap-Plugin