小程序开发中,有些原生组件,比如textarea存在层级太高的问题,一般发生在两种场景:
1.页面较长,然后底部有固定fixed的按钮
2.页面有自定义弹窗时
这两种情况下,textarea中的文字都会穿透固定按钮和弹窗浮在最上层。找了很多方法,可能最合适的就是自定义一个替代元素,以下附上完整的代码(wepy框架小程序):
template中的html:
<view class="demo">
<textarea class="weui-textarea" maxlength='150' auto-focus="isFocus" @blur="bindContentBlur" value='{{mediaDemo}}' @input="bindTextAreaBlur" wx:if="{{isInputContentFocus}}" placeholder="请输入媒体详情" placeholder-class="phClass"></textarea>
<!-- 下面是替代元素 -->
<scroll-view scroll-y class="content" @tap="bindContentFocus" wx:if="{{isContentFocus}}">
<div class="placeholder" wx:if="{{!mediaDemo}}">请输入媒体详情</div>
<div style="word-wrap:break-word;word-break:break-all;" wx:else>{{mediaDemo}}</div>
</scroll-view>
</view>
data中涉及到的变量:
data={
mediaDemo: '',
isContentFocus: true,
isInputContentFocus: false,
isFocus: false,
}
methods中的方法:
methods = {
bindTextAreaBlur(e) {
this.mediaDemo = e.detail.value;
this.$apply();
},
bindContentFocus() {
this.isFocus = true;
this.isContentFocus = false;
this.isInputContentFocus = true;
this.$apply();
},
bindContentBlur() {
this.isContentFocus = true;
this.isInputContentFocus = false;
this.isFocus = false;
this.$apply();
}
};
style中的样式:
.weui-textarea {
border: 1px solid #afb8cd;
background: #fff;
padding: 20rpx;
border-radius: 5rpx;
height: 150rpx;
margin: 30rpx auto 100rpx auto;
width: 86%;
}
.content {
margin: 30rpx auto 100rpx auto;
border: 1px solid #afb8cd;
background: #fff;
padding: 15rpx 20rpx 26rpx 20rpx;
border-radius: 5rpx;
height: 150rpx;
width: 86%;
}
.phClass,
.placeholder {
color: #999;
}