#夏日挑战赛#【FFH】鸿蒙Js API8之新增Dom的动态添加 原创 精华
鸿蒙Js API8之新增Dom的动态添加
不久前鸿蒙js更新到了api8,看了一下官方文档关于API8的新增内容,发现了这样一个新增
https://developer.harmonyos.com/cn/docs/documentation/doc-releases/apidiff-js-api-8-arkui-0000001276484188
新增了dom的接口
static createElement(tag: string): Element
调用示例如下:
viewmodel的Element接口新增三个关于Dom的操作
addChild(child: Element): void;
setAttribute(name: string, value: string): void;
setStyle(name: string, value: string): boolean;
实例演示
尝试添加image的dom
点击addImage生成image的dom
调用createElement(‘image’) ,返回Element
let image=dom.createElement(‘image’)
设置image的src属性
image.setAttribute(‘src’,‘/common/testImage.png’)
调用addChild(ELement)添加到指定组件下
this.$element(‘div2add’).addChild(image)
完整代码
相当于代替了js组件的show或if属性
尝试添加input的dom
(因为设置不了text组件的显示内容,用input的text类型替代显示)
添加成功,但设置的font-size:50px样式没有生效
总结
Web框架中js对dom的操作是非常方便实用的,既然ArkUI是类Web框架的,对Dom树增加更多的操作接口是很有必要的,它能更大的提高开发效率。从新增的dom接口来看,这个方向也在逐渐的建立和完善,希望接下来的js API版本更新能给ArkUI前端开发带来更多的惊喜和便利。
期待完善的功能
目前createElement生成的dom貌似设置不了自身style,但能通过在其父组件中设置子组件样式来改变
尝试新增的setStyle()接口:
Sets a style value on a specified element. If the style exists and the style value is valid, the setting is successful. Otherwise, the setting is invalid.
@param name style name
@param value style value
@returns If the setting is successful, true is returned. If the setting fails, false is returned.
@since 8
setStyle(name: string, value: string): boolean;
到api8后能玩的也是越来越多了,变动的文档楼主方便贴一下吗
你好,问一下,你的dom对象从哪里引入的?
不需要引入,createElement()是static方法,直接调用dom.createElement(tag:'string')就能返回一个Element对象
已贴,暂时还没有具体的接口说明文档,但能在ts文件找到
现在只是能够创建DOM,不能像网页端一样控制DOM吧。
如果能,那就有的玩了