官网文档地址
安装
使用包管理器
推荐使用包管理器进行安装:
# 选择一个你喜欢的包管理器
# NPM
$ npm install pinyin-pro --save
# Yarn
$ yarn add pinyin-pro
# pnpm
$ pnpm install pinyin-pro
浏览器直接引入 CDN
<script src="https://unpkg.com/pinyin-pro"></script>
<script>
var { pinyin } = pinyinPro;
pinyin('汉语拼音'); // 'hàn yǔ pīn yīn'
</script>
我们要制作的是一个 根据用户的输入 在上方显示对应文字的汉语拼音
html
<div class="one">
<input type="text" name="" id="show" placeholder="对应的拼音显示">
<input type="text" id="shuru" placeholder="在这里输入汉字..">
</div>
CSS
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
width: 100%;
height: 100vh;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
}
.one {
width: 40%;
height: 30%;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
/* background-color: #00FFEE; */
border-radius: 20px;
}
input {
border: 0;
height: 32px;
border: 2px solid black;
padding: 16px;
border-radius: 10px;
}
#show{
font-size: 20px;
}
#shuru{
margin-top: 20px;
font-size: 20px;
letter-spacing: 5px
}
js
var { pinyin } = pinyinPro;
let ipt = document.querySelector('#shuru')
let ipt1 = document.querySelector('#show')
console.log(ipt1);
ipt.addEventListener('input', debounce(function() {
let p = pinyin(`${ipt.value}`)
console.log(p);
ipt1.value = p
}))
// 写一个防抖函数
function debounce(fn) {
let timer = null
return function () {
if (timer) { clearTimeout(timer) }
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, 500)
}
}