The author of this article: Peerless, GitHub link: github.com/wushuangzha…

This paper introduces how to preview pictures in rich-text in baidu intelligent small program development. Welcome developers to share your experience in the development of intelligent small program, we will share your experience to more developers through the community channels of intelligent small program technical team, submission address: [email protected].

In a small program, rich text can be used to display rich text through the rich-text component, but the smart applet will block events on all nodes within the rich-text (see the rich-text documentation in the Bug&Tip section). We cannot implement the corresponding business logic by directly binding the image click event in rich-text. When we need to preview an image in rich-text, how do we do that?

This article introduces you to the following two scenarios:

  • Scheme 1: Bind tap events to the rich-text component.

  • Solution 2: Use the rich text parsing tool -bdParse(this component contributes components for developers), by escaping the node type into separate elements, such as => , and then binding click events to the image component to achieve the function of clicking on the image preview.

Solution 1: Bind tap events to the rich-text component.

Implementation principle:

The rich-text component screens all node events, but provides support for default events, including tap, TouchStart, TouchMove, TouchCancel, Touchend and Longtap. Here we use the tap event:

Implementation steps

  1. Get user click location

    In the swan file, tap event is used to obtain the rich-text coordinate (x,y) of the click content, that is, the specific location of the user’s click.

    <rich-text nodes="{{content}}" bindtap="getClickInfo"></rich-text>
    Copy the code

  1. Gets the rendered position of the image

    After obtaining the specific position of the rich-text, we can query in the JS file through createSelectorQuery() to obtain the position of the image after rendering.

   swan.createSelectorQuery().selectAll('.rich-text-img').fields({rect: true}).exec((res)=> {
       console.log(res)
       }
   )
Copy the code

The purpose of this is to confirm the click range: assuming the image is 126px from the top of the screen and 375px from the bottom of the image, the user has clicked on the image as long as the click area is within this range, and the default width is 100%.

  1. Implement image preview in JS file

    Once we know where the image is and where the user clicked, we can call previewImage to preview.

  swan.previewImage({
       urls: this.data.images,
       current: this.data.images[imageIndex]
   })
Copy the code

More about slide when image rendering and user operation handling of altitude change, everybody can be the following code fragment into developer tools, preview: swanide: / / / ff1c48cca302b06c598aa4128dc6ece51584432236472 fragments

Solution 2: Use rich text parsing tools -bdParse

BdParse: Adapted from WxParse to support HTML conversion into smart applet rich text nodes. This component contributes components for developers.

Realize the principle of

NPM install@smt-lib /bdparse installs the lib library. Bdparse already has many built-in features, including support for converting HTML nodes to JSON format:

  • Bdparse supports converting HTML nodes to JSON format. The bdparse. swan file already contains templates for many components, including converting HTML nodes to JSON format via bdparse. js:
	nodes:[
		{
	     "node": "element"."tag": "img"."index": "0.2"."tagType": "inline"."classStr": "custom-img"."attr": {
	      "src": "http://5b0988e595225.cdn.sohucs.com/images/20180605/3cb1f7e7bdae4c5aa4e7aa62ede169ab.jpeg"."class": "custom-img"
	     },
	     "imgIndex": 0."from": "article"}]Copy the code
  • BdParse supports image preview by looping through the Templeta template to bind jSON-formatted data to the current image component, such as in bdparse. swanbdParseImgImage template:
<template name="bdParseImg">
  <image class="{{item.classStr}} bdParse-{{item.tag}}" data-from="{{item.from}}" data-src="{{item.attr.src}}"  data-idx="{{item.imgIndex}}" src="{{item.attr.src}}"  bindload="bdParseImgLoad" bindtap="bdParseImgTap" mode="aspectFit" style="width:{{item.width}}px; height:{{item.height}}px;"/>
</template>
Copy the code
  • BdParse supports image click events built into bdparse.js:
// Image click eventfunction bdParseImgTap(e) {
  var that = this;
  var nowImgUrl = e.target.dataset.src;
  var tagFrom = e.target.dataset.from;
  if(typeof (tagFrom) ! ='undefined'&& tagFrom.length > 0) {swan.previewImage({current: nowImgUrl, // HTTP url of the current image: That.data[tagFrom].imageurls // List of HTTP links to preview images})}}Copy the code

Implementation steps

  1. Convert the original content into the content to be displayed in the JS file.
    Page({data: {raw:[// need to convert the raw content of the presentation'<div>'.' I'm HTML code '.'<span>'.'content'.'</span>'.'<img src="https://b.bdstatic.com/miniapp/images/demo-dog.png" class="custom-img" />'.'</div>'
            ].join('\n')}});Copy the code

    Here we userawIn addition to this property, BDPARs also provides format and padding properties for developers to use as needed. The attribute description list is as follows:

The property name type mandatory The default value instructions
raw String is ‘ ‘ The original content of the presentation needs to be transformed
format String no ‘html’ Need to convert content to original format, options are: ‘HTML ‘, ‘markdown’
padding Number no 5 Left and right white space of the rendered interface (px units)
  1. Use the BdParse plug-in in the swan file.
    <view class="card-area">
        <view class="top-description border-bottom"</view> <view class="text-content">{{raw}}</view>
    </view>
    
    <view class="card-area {{converted ? 'show': 'hide'}}">
        <view class="top-description border-bottom"</view> <view class="text-content">
            <bdparse raw={{raw}} />
        </view>
    </view>
    
    Copy the code
  2. Set the style in the CSS file:
    .custom-img { width: 100% ! important; }Copy the code

More details can be the following code fragment into developer tools, preview: swanide: / / fragments / 80138 c592c5052fe0e8938c27c501fce1580812312899

conclusion

This article provides you with two methods:

  • The advantage of binding tap event to the rich-text component is to improve performance. As we know, the more nodes rendered, the more performance is consumed. This scheme can avoid generating more nodes and shorten the page rendering time.

In addition to images, in fact, as long as we get the location of the user needs to operate and the location of the required elements, we can use this method to achieve the functions of clicking on an image, playing a video, clicking or copying text.

  • Using the rich text parsing tool -bdParse saves development time by using wrapped plug-ins. However, when the content of a text is long, new components can be generated by escaping more, increasing memory and rendering time.

You are advised to use different methods based on your actual application scenarios.

Intelligent small developers community article links: smartprogram.baidu.com/forum/topic…

Finally, thank you for your active participation in the development of Baidu small program, any problems in the development process can be in the community to interact with the official or other developers, you can also send your comments to [email protected], looking forward to your participation!