Руководство по страницам может дать пользователям полезные подсказки при первом посещении веб-сайта. Следующее введение основано наreactНаписан постраничный компонент.демонстрационный адрес
визуализация
Реализация компонента Guide
можно поставить<Guide/>Разработан как компонент-контейнер, потому что мы не знаем, какой контент нужно направлять через компонент-контейнер.this.props.childrenвизуализировать содержимое
class Guide extends Component {
render () {
return (
<div className="guide-container" ref={e => this.guide = e}>
{this.props.children}
</div>
)
}
}
Как получить, какие из них для загрузкиdomВы можете передать пользовательские атрибуты dom, а затем передатьquerySelectorAllПолучать
// example
<Guide >
<header data-step="1" data-tip='Welcome to use react-guide'>React Guide</header>
</Guide>
// 获取要引导的dom
this.guide.querySelectorAll('[data-step]')
<Guide/>Компонент также должен иметь: слой маски, окно подсказки, область содержимого, голосовую функцию, 4 части.
маскирующий слой
слой маски черезfixedМакет, просто добавьте прозрачности, он исходит извнеvisibleдисплей управления
class Guide extends Component {
render () {
return (
<div className="guide-container" ref={e => this.guide = e}>
{this.props.children}
{this.props.visible&&<div className="guide-shadow" ref={e => this.shadow = e}s.onClickShadow.bind(this)} key='guide-shadow'></div>}
</div>
)
}
}
Подсказка
Подсказка должна быть поверх слоя маски, ееz-indexОн больше, чем слой маски. В поле подсказки также следует учитывать свободное пространство на странице, чтобы определить положение размещения. Как показано на следующем рисунке, 4 позиции, 1 и 4 позиции не могут быть размещены, поэтому 2 и 3 могут быть размещены размещен.
добавитьresizeСлушатель событий, также может изменять макет при увеличении страницы.
window.addEventListener('resize', this.onRezieWindow.bind(this), false)
Область содержимого
Сначала определите, где отображать область контента, ориентируясьdomизoffsertLeft,offsetTop,height,width, получить расположение области содержимого
const nodeList = getListFromLike(this.guide.querySelectorAll('[data-step]')) // 获取所有要引导dom
nodeList.sort((a, b) => {
return Number(a.getAttribute('data-step'))- Number(b.getAttribute('data-step'))
}) // 按照step的大小进行排序
let dots = nodeList.map(node => {
let height = node.clientHeight || node.offsetHeight
let width = node.clientWidth || node.offsetWidth
return {
left: node.offsetLeft,
top: node.offsetTop,
height,
width,
tip: node.getAttribute('data-tip'),
step: node.getAttribute('data-step'),
fRight: node.offsetLeft + width,
fBottom: node.offsetTop + height
}
})
Область содержимого также находится поверх слоя маски.contentпросто дайте оригиналdomдобавитьz-index
node.style.setProperty('position', 'relative');
node.style.setProperty('z-index', '999996', 'important');
Когда на странице есть полоса прокрутки, прокрутите страницу до нужной области,scrollTo(x, y)выполнить
window.scrollTo(dLeft - 100, dTop - 100)
Голосовая функция
доступна голосовая функцияHTML5изaudioЭтикетка
<audio ref={e => this.audio = e} src={this.state.audioUrl} type="audio/mpeg"></audio>}
В сочетании с BaiduttsизAPI
function text2Voice(tip, lan){
let obj = {
lan,
ie: 'UTF-8',
spd: '4',
per: 4,
text: tip // tip就是dom上data-tip的属性值
}
return 'http://tts.baidu.com/text2audio' + axiosObj(obj)
}
Пучокaudioпомеченsrcнаправлениеtext2Voice(tip, lan)результат
пройти черезaudioизapiУправляй остановкой, играй
this.audio.autoplay = true // 自动播放
this.audio.pause() // 暂停
this.audio.addEventListener('timeupdate', () => {
... // 监听什么时候结束
}, false)
иллюстрировать
исходный код иapi➡️github, Добро пожаловатьstar,благодарный.
Установить
в состоянии пройтиnpmУстановить
$ npm install react-guide
API
Нижеreact-guideизapi
| Property | Description | Type | Default |
|---|---|---|---|
| visible | Whether the guide is visible or not | boolean | false |
| audio | Whether a voice reads of tip of the guide or not | boolean | true |
| lan | The voice of language, 'en' or 'zh' | string | en |
| bullet | Whether bullets (.) button is visible on middle of the guide or not | boolean | false |
| num | Whether num icon is visible on top left of the guide or not | boolean | false |
| onCancel | Specify a function that will be called when a user clicks shadow, skip button on bottom left | function(e) | - |
| onOk | Specify a function that will be called when all steps have done and click the done button | function(e) | - |
| data-step | Number of steps for guides, only use in dom | string | - |
| data-tip | Every step you want to show tip, only use in dom | string | - |
пример
один пример
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Guide from 'react-guide'
class App extends Component {
constructor () {
super()
this.state = {
visible: false
}
}
handleStart() {
this.setState({
visible: true
})
}
handleCancel() {
this.setState({
visible: false
})
}
render() {
return (
<div>
<Guide
visible={this.state.visible}
onCancel={this.handleCancel.bind(this)} >
<h1 data-step="1" data-tip='Hello World'>Step1</h1>
<div data-step="3" data-tip='Welcome to use react-guide'>Step3</div>
<h4 data-step="2" data-tip='react-guide is very easy' >Step2</h4>
<div><span data-step="4" data-tip='Let start'>Step4</span></div>
</Guide>
<button onClick={this.handleStart.bind(this)}>start</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));