1、slide轮播图无法滑动
2、如何在html赋值参数,然后在mui的事件里面获取
3、如何手动关闭当前页面
4、子页面传递参数给父页面
5、保留小数点后2位,不会四舍五入
6、关闭多个页面与当前页面
7、通过document.createElement创建的div,如何设置自定义属性?
8、如何去除video的默认图片?
9、如何获取拍照的图片,相册的图片
10、如何执行上一个页面的JS
11、关闭当前页面和上一个页面
12、mui混合开发,如何替换默认的splash图片
13、mui混合开发,base64保存为图片,并且分享到微信里面
14、mui混合开发,base64保存为图片且保存到相册
1、slide轮播图无法滑动
最开始写静态数据的时候,是可以滑动的,但是当与后台数据相互结合的时候,就无法滑动了
静态数据写法
mui.plusReady(function (){
addGoods(); //注意这一块
mui('.mui-slider').slider({interval: 2000 }); //注意这一块
)}
function addGoods(){
var slider_img = document.querySelector('.mui-slider-group');
var slider_point = document.querySelector('.point-list');
var flags = 0;
var classFlag = '';
for(var i=0; i<imgList.length; i++){
var div = document.createElement('div');
if(i == 0){
flags = imgList.length -2;
div.className = 'mui-slider-item mui-slider-item-duplicate'
}else if(i == imgList.length -1){
flags = 1;
div.className = 'mui-slider-item mui-slider-item-duplicate'
}else{
flags = i;
div.className = 'mui-slider-item'
}
div.innerHTML = '<a href="#"><img src="'+imgList[flags]+'"></a>';
slider_img.appendChild(div);
}
for(var j=0; j<imgList.length-2; j++){
var pointItem = document.createElement('div');
if(j == 0) pointItem.className = 'mui-indicator mui-active';
else pointItem.className = 'mui-indicator';
slider_point.appendChild(pointItem)
}
}
动态数据写法,这样的写法会导致你无法滑动
mui.plusReady(function (){
readData(); //注意这一块
mui('.mui-slider').slider({interval: 2000 }); //注意这一块
)}
function readData() {
ajaxPost('/wap/index.html', {}, function(res) {
if (res.status == 1) {
addGoods(res.result);
}
})
}
解决办法
mui.plusReady(function (){
readData();
)}
function readData() {
ajaxPost('/wap/index.html', {}, function(res) {
if (res.status == 1) {
addGoods(res.result);
}
})
}
function addGoods(result) {
imgList = imgList.concat(result.banner_list);
if (imgList && imgList.length > 0) {
imgList.splice(1,0, imgList[imgList.length - 1]);
imgList.push(imgList[0]);
}
var slider_img = document.querySelector('.mui-slider-group');
var slider_point = document.querySelector('.point-list');
var classFlag = '';
for (var i = 0; i < imgList.length; i++) {
var div = document.createElement('div');
if (i == 0) {
div.className = 'mui-slider-item mui-slider-item-duplicate'
} else if (i == imgList.length - 1) {
div.className = 'mui-slider-item mui-slider-item-duplicate'
} else {
div.className = 'mui-slider-item'
}
div.innerHTML = '<a href="#"><img src="img/banner_2.png"></a>';
slider_img.appendChild(div);
}
for (var j = 0; j < result.banner_list.length; j++) {
var pointItem = document.createElement('div');
if (j == 0) pointItem.className = 'mui-indicator mui-active';
else pointItem.className = 'mui-indicator';
slider_point.appendChild(pointItem)
}
//注意这里
mui('.mui-slider').slider({
interval: 2000
})
}
我将mui('.mui-slider')放到成功请求数据的后面了
2、如何在html赋值参数,然后在mui的事件里面获取
mui('.to-goods').on('tap', '.goods-item', function() {
var goods_id = this.dataset.id;//获取到id的值
mui.openWindow({
url:"pages/goods/goodsDetail.html",
id:"goodsDetail",
extras:{
goods_id:goods_id,//商品ID
},
});
})
//动态渲染html代码 注意:data-id,这里的id值要与上面function里面的id参数名字对上
for (var i = 0; i < item.goods_list.length; i++) {
var smlitem = item.goods_list[i];
goods_item += '<div class="goods-item" data-id='+smlitem.goods_id+'><div class="imgs"><img src="' + smlitem.picurl + '" ></div>' +
'<div class="b-line2 tell">' + smlitem.goods_name + '</div>' +'</div>';
}
3、如何手动关闭当前页面
//获取当前的ID
var currentid = plus.webview.currentWebview().id;
plus.webview.close(currentid);//关闭页面
4、子页面传递参数给父页面
//子页面 applyOrder是启动父页面的id,所以你得先拿到父页面的ID填入进去
//addressEventListener 是自己定义的名称
var main=plus.webview.getWebviewById("applyOrder");
mui.fire(main,'addressEventListener',{addressid:res.result.address_id});
//父页面 监听的参数要放到 mui.plusReady 里面
mui.plusReady(function() {
window.addEventListener("addressEventListener", function(e) {
console.log(e.detail.addressid);
});
}
5、保留小数点后2位,不会四舍五入
var totalAmount = vm.goods_price * 1 + vm.shipping_price * 1;
totalAmount = totalAmount.toFixed(3);
vm.hanyoufei=totalAmount.substring(0,totalAmount.lastIndexOf('.')+3);
6、关闭多个页面与当前页面
var oldBack = mui.back;
mui.back = function(){
//关闭当前页面和上一个页面
//当前窗口对象
var self = plus.webview.currentWebview();
var wvs = plus.webview.all();
for (var i = 0; i <= wvs.length-1; i++) {
if(wvs[i].id =="applyOrder"){//这个是上一个页面的名字
plus.webview.close(wvs[i]);
break;
}
}
self.close("none");//避免闪屏
}
7、通过document.createElement创建的div,如何设置自定义属性?
var div = document.createElement('div');
div.setAttribute("data-id",item.article_id);//就这样可以设置自定义的属性值了
8、如何去除video的默认图片?
![](https://img.haomeiwen.com/i1945114/38ec3839c9325e14.png)
<video width="100%" height="100%" controls="controls" preload="auto" poster="../../img/icon_white.png" >
<source :src="video" type="video/mp4" />
</video>
//加一个poster参数,并设置图片路径,我这里设置的是白色的图片
![](https://img.haomeiwen.com/i1945114/d05cea6a8d30ac9e.png)
9、如何获取拍照的图片,相册的图片
//拍照的图片
var cmr = plus.camera.getCamera();
cmr.captureImage(function(p){
plus.io.resolveLocalFileSystemURL(p, function(entry){
var imgSrc = entry.toLocalURL(); //拿到图片路径
vm.gerenerwema = imgSrc;
}, function(e){
mui.toast("读取拍照文件错误");
});
}, function(e){
mui.toast("失败:");
}, {filename:'_doc/camera/',index:1});
//拿到相册的图片
plus.gallery.pick( function(path){
vm.gerenerwema = path;
}, function ( e ) {
}, {filter:"image"} );
10、如何执行上一个页面的JS
// A.html 重新请求数据
window.addEventListener('reloadData', function(event){
plus.nativeUI.showWaiting();
//如果要获取参数应该这样写 var id = event.detail.id;
readData();
});
//B.html 首先getWebviewById一定要是A启动的时候的ID,其次reloadData一定要与A.html里面的对应
mui.back = function() {
var view = plus.webview.getWebviewById('A');
mui.fire(view, 'reloadData', {});
//如果要传递参数应该这写 mui.fire(view, 'reloadData', {id:'aaaa'});
}
11、关闭当前页面和上一个页面
//关闭页面
function closepage(){
//关闭当前页面和上一个页面
//当前窗口对象
var self = plus.webview.currentWebview();
var wvs = plus.webview.all();
for (var i = 0; i <= wvs.length - 1; i++) {
if (wvs[i].id == "serviceType") {//上一个页面
plus.webview.close(wvs[i]);
break;
}
}
self.close("none"); //关闭当前页面
}
12、mui混合开发,如何替换默认的splash图片
1、在mui提供的as,demo里面含有一个类叫WebappModeListener,里面有个View是splashView,我们只需要操作一下这个就OK了
我只贴出需要修改的地方的代码
app = SDK.startWebApp(activity, appBasePath, args, new IWebviewStateListener() {
// 设置Webview事件监听,可在监监听内获取WebIvew加载内容的进度
@Override
public Object onCallBack(int pType, Object pArgs) {
switch (pType) {
case IWebviewStateListener.ON_WEBVIEW_READY:
// WebApp准备加载事件
// 准备完毕之后添加webview到显示父View中,
// 设置排版不显示状态,避免显示webview时html内容排版错乱问题
View view = ((IWebview) pArgs).obtainApp().obtainWebAppRootView().obtainMainView();
view.setVisibility(View.GONE);
if(view.getParent() != null){
((ViewGroup)view.getParent()).removeView(view);
}
rootView.addView(view, 0);
break;
case IWebviewStateListener.ON_PAGE_STARTED:
// 首页面开始加载事件
//pd = ProgressDialog.show(activity, "加载中", "0/100");
break;
case IWebviewStateListener.ON_PROGRESS_CHANGED:
// WebApp首页面加载进度变化事件
/*if (pd != null) {
pd.setMessage(pArgs + "/100");
}*/
break;
case IWebviewStateListener.ON_PAGE_FINISHED:
// WebApp首页面加载完成事件
/*if (pd != null) {
pd.dismiss();
pd = null;
}*/
app.obtainWebAppRootView().obtainMainView().setVisibility(View.VISIBLE);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
rootView.removeView(splashView);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
break;
}
return null;
}
}, this);
这里我把ProgressDialog给注释掉了,因为我们不需要这个
@Override
public Object onCreateSplash(Context pContextWrapper) {
splashView = new FrameLayout(activity);
splashView.setBackgroundResource(R.drawable.back_splash);//这里设置背景图片,这样就可以替换mui默认的splash
rootView.addView(splashView);
return null;
}
@Override
public void onCloseSplash() {
// rootView.removeView(splashView);
}
style风格更改的地方
<application
android:allowBackup="true"
android:icon="@mipmap/icon_log"
android:label="@string/app_name"
android:name=".base.BaseApplication"
android:roundIcon="@mipmap/icon_log"
android:supportsRtl="true"
tools:replace="android:name"
android:theme="@style/AppTheme">
<activity
android:name=".SDK_WebApp"
android:configChanges="orientation|keyboardHidden|keyboard|navigation"
android:label="@string/app_name"
android:launchMode="singleTask"
android:hardwareAccelerated="true"
android:theme="@style/MyDCloudTheme"
android:screenOrientation="user"
android:windowSoftInputMode="adjustResize" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
style:MyDCloudTheme的xml代码
<style name="MyDCloudTheme" parent="@style/DeviceDefault.Light">
<item name="android:windowFullscreen">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
</style>
如果发现splash图片在各个平台手机里面会变形的话,建议创建一个layout.xml,然后引用它就OK了
view backGroundView = LayoutInflater.from(activity).inflate(R.layout.view_background,null);
....省去很多代码,然后将splashView的删除
rootView.addView(backGroundView);
13、mui混合开发,base64保存为图片,并且分享到微信里面
需要引入的js: html2canvas.min.js
<script type="text/javascript">
var buttons=[
{title:'我的好友',extra:{scene:'WXSceneSession'}},
{title:'朋友圈',extra:{scene:'WXSceneTimeline'}}
];
var sweixin=null;
mui.plusReady(function() {
//这部分是固定的写法
plus.share.getServices(function(s){
shares={};
for(var i in s){
var t=s[i];
shares[t.id]=t;
}
sweixin=shares['weixin'];
}, function(e){
console.log('获取分享服务列表失败:'+e.message);
});
});
// 分享图片,index=0表示是微信,1为朋友圈,触发的方法是以这个为开始触发的
function shareImage(index){
//这里是你要生成最后的高度,各位可以根据自己的需求修改高度,宽度
var height = document.getElementById("shareimgbg").clientHeight;
var width = document.getElementById("shareimgbg").clientWidth;
var canvas = document.createElement("canvas")
canvas.width = width
canvas.height = height
var opts = {
canvas: canvas, // 将自定义canvas作为配置项
useCORS: true,// 允许图片跨域
height: height // 修复截图不完整问题
}
//document.getElementById("sharepic"),获取的是哪部分是需要裁剪出来的,记住一点,裁剪的部分必须要显示,如果是隐藏的,就会出现白色的
html2canvas(document.getElementById("sharepic"), opts).then((canvas) => {
var base64ImgSrc = canvas.toDataURL("image/png");
var msg={type:'image'};
if(!base64ImgSrc){
plus.nativeUI.alert('请选择要分享的图片!');
return;
}
save64ToPic(base64ImgSrc,1,function(picurl){
msg.pictures=[picurl];
share(sweixin, msg, buttons[index]);//调用分享
})
})
}
// 分享
function share(srv, msg, button){
button&&(msg.extra=button.extra);
// 发送分享
if(srv.authenticated){
console.log('---已授权---');
doShare(srv, msg);
}else{
console.log('---未授权---');
srv.authorize(function(){
doShare(srv, msg);
}, function(e){
console.log('认证授权失败:'+JSON.stringify(e));
});
}
}
// 发送分享
function doShare(srv, msg){
srv.send(msg, function(){
console.log('分享到"'+srv.description+'"成功!');
}, function(e){
console.log('分享到"'+srv.description+'"失败: '+JSON.stringify(e));
});
}
//base64是字符串
//quality图片质量1-100
//callback成功回调函数
function save64ToPic(base64, quality, callback) {
var timestamp=new Date().getTime()
quality = quality || 10;
var bitmap = new plus.nativeObj.Bitmap();
// 从本地加载Bitmap图片
bitmap.loadBase64Data(base64, function() {
bitmap.save("_doc/" + timestamp + ".png", {
overwrite: true,
quality: quality
}, function(i) {
callback(i.target);//获取到图片的地址
}, function(e) {
console.log('保存图片失败:' + JSON.stringify(e));
});
}, function(e) {
console.log('加载图片失败:' + JSON.stringify(e));
});
}
</script>
14、mui混合开发,base64保存为图片且保存到相册
//outputWidth,outputHeight下载的宽高,
//elementId使用哪个div去生成图片
//需要引入html2canvas.min.js
//所有参数必填
function downToGallery(outputWidth,outputHeight,elementId){
var canvas = document.createElement("canvas")
canvas.width = outputWidth // 最终图片宽度280px的2倍,以px为单位
canvas.height = outputHeight // 最终图片高度315px的2倍,以px为单位
var opts = {
canvas: canvas, // 将自定义canvas作为配置项
useCORS: true, // 允许图片跨域
height: outputHeight // 修复截图不完整问题
}
html2canvas(document.getElementById(elementId), opts).then((canvas) => {
var base64ImgSrc = canvas.toDataURL("image/png");
var msg = {
type: 'image'
};
if (!base64ImgSrc) {
return;
}
save64ToPic(base64ImgSrc,1,function(picurl){
plus.gallery.save(picurl,function(){
mui.toast('保存成功');
},function(){
mui.toast('保存失败,请重试!');
})
});
})
}
//base64是字符串
//quality图片质量1-100
//callback成功回调函数
function save64ToPic(base64, quality, callback) {
var timestamp = new Date().getTime()
quality = quality || 10;
var bitmap = new plus.nativeObj.Bitmap();
// 从本地加载Bitmap图片
bitmap.loadBase64Data(base64, function() {
bitmap.save("_doc/" + timestamp + ".png", {
overwrite: true,
quality: quality
}, function(i) {
callback(i.target);//目标图片
bitmap.recycle();
}, function(e) {
console.log('保存图片失败:' + JSON.stringify(e));
});
}, function(e) {
console.log('加载图片失败:' + JSON.stringify(e));
});
}
//使用方法,举个例子
downToGallery(200,300,"adbc");
网友评论