Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement a label input box based on native CSS+JS

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article "how to achieve a tag input box based on native CSS+JS" is not understood by most people, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to achieve a tag input box based on native CSS+JS" article.

Recently, we need to make a label input box in the project, which is quite practical. The demonstration effect is as follows:

The main interaction requirements are as follows:

Click the input box to enter the content.

Press enter to generate a label.

Press the Backspace key to delete the label.

Click the close button on the tab to delete the tag.

Adaptive input box layout

No matter what component, layout is the most important. This layout is divided into two parts: label and input box, assuming that the HTML is as follows:

CSS

A simple embellishment:

.tags-content {display: flex; flex-wrap: wrap; align-items: flex-start; gap: 6px; width: 400px; box-sizing: border-box; padding: 8px 12px; border: 1px solid # D9D9D9; border-radius: 4px; font-size: 16px; line-height: 24px; color: # 333; outline-color: # 4F46E5; overflow: auto; cursor: text;} tag {display: flex Align-items: center; padding: 4px 0 4px 8px; font-size: 16px; line-height: 24px; background: # F5F5F5; color: rgba (0,0,0,0.85); cursor: default;} tag-close {width: 18px; height: 18px; cursor: pointer Background: url ("data:image/svg+xml % 3Csvg width='10' height='10' viewBox='0 0 10 10 'fill='none' xmlns=' http://www.w3.org/2000/svg'%3E%3Cpath d='M5.578 5l2.93-3.493a.089.089 0 0 0-.068-.146h-.891a.182.182 0 0 0-.137.064l-2.417 2.88-2.416-2.88a.178.178 0 0 0-.137-.064h-.89a.089.089 000- .069.146L4.413 5l-2.93 3.493a.089.089 000.068.146h.89a.182.182000.138-.064l2.416-2.88 2.417 2.88c.033.04.083.064.137.064h.89a.089.089 000.069-.146l-2.93-3.493z' fill='%23000' fill-opacity='.45'/%3E%3C/svg%3E ") center no-repeat }. Tags-input {flex: auto; border: 0; outline: 0; padding: 4px 0; line-height: 24px; font-size: 16px;} .tags-content:focus-within,.tags-content:active {outline: auto # 4F46E5;}

Note a few implementation techniques:

The interval between tags can be implemented in gap.

To fill the area of the input box with the remaining space, flex: auto is used here.

To keep the parent in focus, focus-within is used here.

The effect is as follows:

However, there are some problems with using input in the input box here, as shown below:

Because the input input cannot follow the width adaptively, sometimes the text is truncated:

Ideally, when there is more input, you should wrap the line as a whole. How can it be realized? It can be implemented with ordinary div.

CSS

This can be achieved by adding contenteditable or the following CSS:

.tags-input {- webkit-user-modify: read-write-plaintext-only;}

This attribute indicates that only plain text is allowed. If you are interested, you can refer to Zhang Xinxu's article: small tip: how to make contenteditable elements only enter plain text [1].

This allows you to adapt to the content width.

Second, input box placeholder prompt

Since the input box has been changed from input to ordinary div tags, there is no placeholder feature. However, we can still achieve the placeholder effect through other CSS features. When there is no content in the input box, we can match to: empty selector, and then dynamically generate placeholder content through the pseudo element:: before, as shown below:

.tags-input:empty::before {content: attr (placeholder); color: # 828282;}

The effect is as follows:

This is almost consistent with the space-occupying effect of input.

In another case, if you need to display placeholders only without any tags, how do you do that? As you can imagine, without any tags, HTML looks like this:

In this case, only the unique element of the input box is left, and the unique element can be matched by: only-child, so the implementation is as follows:

.tags-input:only-child:empty::before {content: attr (placeholder); color: # 828282;}

This is solved by adding a pseudo class.

Both requirements are in line with cognition, depending on how the design determines.

III. Input and deletion of tags

To achieve the input and deletion of tags, you need to JS. You only need to listen to the keyboard's "enter" and "backspace" keys. It should be noted that by default, line breaks occur when ordinary contenteditable elements enter, as follows:

Therefore, when listening for keyboard events, you need to block the default event, then dynamically create a tag element and add it to the front of the input box through before, as follows:

/ / TagInput is the input box TagInput.addEventListener ('keydown', function (ev) {if (ev.key = =' Enter') {ev.preventDefault () if (this.innerText) {/ / the contents of the input box get const tag = document.createElement ('TAG') through innerText; tag [XSS _ clean] = this.innerText +'; this.before (tag); this.innerText ='';})

In this way, the tag can be created normally.

Then there is the deletion of the label.

There are two ways. First, look at the deletion of the keyboard. The specific logic is to delete the tag when the content of the input box is empty. It is very simple. The deleted tag is the first element of the input box, which is obtained through previousElementSibling. The specific implementation is as follows:

TagInput.addEventListener ('keydown', function (ev) {if (ev.key =' Backspace' & &! this.innerText) {this.previousElementSibling?.remove (); / / need to determine whether the previous element exists}})

Then click the delete icon to delete. Because the tags are generated dynamically, you need to add and delete events in the form of event delegates.

/ / TagContent is the parent container TagContent.addEventListener ('click', function (ev) {if (ev.target.className =' tag-close') {ev.target [XSS _ clean] .remove ();} TagInput.focus (); / / Click anywhere in the input box to focus})

This achieves the effect shown at the beginning of the article:

Fourth, choose the framework or the original

Sum up!

The overall implementation is not complicated, a lot of interactive logic CSS can be easily implemented, and JS is only about 10 lines of code. Here is a summary of the main points of implementation:

Plain text input for ordinary div elements can be done using-webkit-user-modify: read-write-plaintext-only

Ordinary div element input can adapt content width

The placeholder occupation of the input box of ordinary div elements can be realized by combining empty with pseudo elements.

The carriage return event needs to block the default event, otherwise the line will be wrapped

You can use the before method to add an element in front of an element

Delete the previous element of an element, you can use the previousElementSibling.remove method

Binding events to dynamically generated elements can be done in the form of event delegates

In the atmosphere of the popularity of various frameworks, some of the native properties and methods may not pay too much attention to, which is a loss. Of course, I myself can use a variety of frameworks, especially large, complex interactive pages, generally relatively small interactions, such as the article this example, there are related components in ant design, also used, because the overall UI is all in this style, the design is also in accordance with this design. Later, we need to develop a separate chrome plug-in, also used such an interaction, but only with such a component, the introduction of the entire framework is too cumbersome, so we choose to directly native implementation, simple and convenient.

The above is about the content of this article on "how to implement a tag input box based on native CSS+JS". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report