JavaScript實現一個輸入框元件
阿新 • • 發佈:2021-09-14
本文例項為大家分享了手動實現一個輸入框元件的具體程式碼,供大家參考,具體內容如下
背景
taro h5中想要實現一個樣式如下的輸入框:
問題:
taro元件和taro-ui元件中都沒有這種樣式的元件,taro h5 中還不支援修改placeholder的樣式,自己嘗試著實現一個input元件,更能靈活的定義其中的樣式。
實現
程式碼
import Taro,{ Component } from '@tarojs/taro'; import { View } from '@tarojs/components'; import { AtIcon } from 'taro-ui'; import './index.s'; /** * @description 手動實現一個輸入框元件 * @param placeholder:String 自定義輸入框中的佔位符 * @param onClicWOVRIcKsxkSearch:Function 獲取輸入內容回撥 */ class BaseInput extends Component { componentDidMount()http://www.cppcns.com { //輸入框聚焦 document.querySelector('.search').focus(); } handleSearch = () => { //獲取輸入框的內容 const value = document.querySelector('.search').innerText; this.props.onClickSearch && this.props.onClickSearch(value); }; render() { const { placeholder = '請輸入' } = this.props; return ( <View className="base_input"> <View className="my_search"> <AtIcon value="search" color="#999" className="search_icon" onClick={this.handleSearch} /> {/* contenteditable可以控制一個div是否可以編輯 */} <View className="search" contenteditable placeholder={placeholder} ></View> </View> </View> ); } } export default BaseInput;
scss程式碼
.base_input { .my_search { box-sizing: border-box; width: 690px; height: 56px; line-height: 56px; border-radius: 28px; margin: 12px auto; background: #f8f8f8; display: flex; .search_icon { width: 30pWOVRIcKsxx; height: 30px; margin-left: 20px; margin-right: 18px; } .search { width: 560px; padding: 0px 18px; background: #f8f8f8; height: 56px; color: #999; font-siwww.cppcns.comze: 28px; font-weight: 400; &:empty::after { content: attr(placeholder); } } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。