为更好地满足个性化定制的需求,百度 H5 提供扩展脚本能力,用户可以通过编写 js 和 css 代码自由控制 H5 页面上的组件。 出于安全考虑,扩展脚本仅支持用于预览和独立部署,不支持用于默认发布。用户可在购买开通扩展脚本部署功能后将脚本用于独立部署的 H5。 扩展脚本的编辑入口在右侧编辑面板的【脚本】tab 下。
H5 同时支持 css 和 js,可利用 <style>
和 <script>
标签来向页面插入自定义的样式和脚本。
<style>
/*可在此处编写自定义组件样式*/
</style>
<script>
$h5.ready(function(){
// 在此处添加自定义 js 代码
});
</script>
自定义 js 脚本的入口,在 H5 初始化后自动调取。
function 扩展脚本的执行函数
代码
<script>
$h5.ready(function(){
alert('test');
});
</script>
通过组件名或规则获取组件实例列表
name {string|Regex|Array} 组件名或者组件名的规则,组件名通过下方时间线面板双击编辑设定。
components {Array}:组件对象数组,即使只有一个符合条件的对象,也会返回一个长度为 1 的数组
<script>
$h5.ready(function(){
let button = $h5.getComponentsByName('button');
console.log(button);
});
</script>
代码
// 示例:时钟效果
<script>
$h5.ready(function(){
let component = $h5.getComponentsByName('labelTime')[0];
function render() {
let now = new Date();
component.instance.attributeChange({
html: '<p style="text-align: center;"><span style="color: #3981eb; font-size: 36px;">' +
[
now.getHours(), now.getMinutes(), now.getSeconds()
].join(':').replace(/\b\d\b/g, '0$&') +
'</span></p>'
});
setTimeout(render, 1000);
}
render();
});
</script>
H5 组件的每个组件外都包裹 .lg-trailer
和 .lg-surface
两个 div 容器。
<!-- trailerElement -->
<div class="lg-trailer">
<!-- sufaceElement -->
<div class="lg-surface">
「组件容器」
</div>
</div>
.lg-surface
是组件的容器,放置特效的地方(边框、阴影).lg-trailer
是动画效果容器(位置和动画)- 获取两个 DOM 元素的方法:
$h5.getComponentsByName('xxx')[0].surfaceElement;
$h5.getComponentsByName('xxx')[0].trailerElement;
隐藏组件
<script>
$h5.ready(function(){
// 兼容移动端和 PC 预览
const clickEvent = (function() {
if ('ontouchstart' in document.documentElement === true)
return 'touchstart';
else
return 'click';
}
)();
let rect = $h5.getComponentsByName('rect')[0];
let button = $h5.getComponentsByName('button')[0];
button.surfaceElement.addEventListener(clickEvent, e => {
rect.hide();
});
});
</script>
<script>
$h5.ready(function(){
// 兼容移动端和 PC 预览
const clickEvent = (function() {
if ('ontouchstart' in document.documentElement === true)
return 'touchstart';
else
return 'click';
}
)();
let rect = $h5.getComponentsByName('rect')[0];
let button = $h5.getComponentsByName('button')[0];
button.surfaceElement.addEventListener(clickEvent, e => {
rect.show();
});
});
</script>
用于更新组件属性的接口,调用方式后续可能更改
[Attributes] 期望更改的属性列表
代码
<script>
$h5.ready(function(){
// 兼容移动端和 PC 预览
const clickEvent = (function() {
if ('ontouchstart' in document.documentElement === true)
return 'touchstart';
else
return 'click';
}
)();
let rect = $h5.getComponentsByName('rect')[0];
let button = $h5.getComponentsByName('button')[0];
button.surfaceElement.addEventListener(clickEvent, e => {
rect.instance.attributeChange({
fill: `rgb(
${parseInt(Math.random() * 256)},
${parseInt(Math.random() * 256)},
${parseInt(Math.random() * 256)})`
});
});
});
</script>