The unhelpful HTML
You guys might think that making a consistent, clean and professional spinbox would be a simple task in HTML... However, to our despair, there is no standard attrib to tell an input that it should only accept integer or decimal values, all input filtering must be JS. Outch!
I'm going to be implementing this functionality with Go, a-h/Templ, Tailwind and my beloved Alpine.js to make life easy.
Adding the Skeleton
We start by writing a basic template for our integer spinbox:
templ IntSpinbox(name, label, value, tooltip string, saveinput bool, interval *IntInterval) { ... }
We define IntInterval as follows:
type IntInterval struct { A, B int }
With the interval, we will set min and max of the input. As we are making an integer spinbox, the step will always be set to '1'.
templ IntSpinbox(name, label, value, tooltip string, saveinput bool, interval *IntInterval) { <input type="number" placeholder="Enter Int…" step="1" if interval nil min="{" strconv.itoa max="{" ...> }
Adding CSS
Let's now start adding some tw classes, following are some special properties and pseudo-elements that control the rendering of the input.
select-none [-moz-user-select:none] [-ms-user-select:none] [-o-user-select:none] [-webkit-user-select:none]
The following extra classes are used to remove the default spinner buttons:
[&::-webkit-inner-spin-button]:[-webkit-appearance:none] [&::-webkit-outer-spin-button]:[-webkit-appearance:none] [-moz-appearance:textfield]
Finally, let's add some basic padding, ring, colors, etc...
block w-full rounded-l-md py-2 px-2.5 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-400 bg-gray-50 sm:text-sm sm:leading-6
Adding it to our template, we get the following:
templ IntSpinbox(name, label, value, tooltip string, saveinput bool, interval *IntInterval) { <input type="number" placeholder="Enter Int…" step="1" if interval nil min="{" strconv.itoa max="{" class="block w-full rounded-l-md py-2 px-2.5 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-400 bg-gray-50 sm:text-sm sm:leading-6 select-none [-moz-user-select:none] [-ms-user-select:none] [-o-user-select:none] [-webkit-user-select:none] [&::-webkit-inner-spin-button]:[-webkit-appearance:none] [&::-webkit-outer-spin-button]:[-webkit-appearance:none] [-moz-appearance:textfield]"> }
Now you should get a very text-like input, with some basic validation if you hover your mouse over it. We will add the functionality to check for valid integer inputs in the next section.
Implementing the Filter
The basic idea of an integer spinbox is of an input that only accepts integers. I initially attempted to implement this function by using HTML's pattern attribute as follows:
<input type="number" pattern="[0-9]+" ...>
The pattern attribute takes a regex string and uses it to validate the user input, however, it doesn't prevent invalid input from being entered in the first place. Actually, it was made for some simple client-side validation.
The 'oninput' event
Every time the user presses any key inside the input box, a oninput event is generated. capture this event with Alpine's syntax x-on:input and rectify the value accordingly for the input element. Let's create a parent div with an x-data attrib set, and add a function that will allow us to check if input is at all a Number... After which we can round the value accordingly.
<div x-data="{isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }}"> <input ... x-on:input="$el.value = isNumber($el.value) ? Math.round($el.value) : null"> </div>
For those who don't know Alpine, $el here is used to refer to the current DOM element.
Custom Spinners
In the parent div created previously, we add the following class="flex" and add an x-ref="spinbox" attrib to the input so that our buttons can modify it's state through the magic property $refs.spinbox:
<div ... class="flex"> <input ... x-ref="spinbox"> </div>
We then add a new child after the input, which will contain our buttons:
<div ...> <input ... x-ref="spinbox"> <div class="flex flex-col-reverse"> <!-- Decrement input's value --> <button type="button" class="flex-1 ...">-</button> <!-- Increment input's value --> <button type="button" class="flex-1 ...">+</button> </div> </div>
Here, we use flex-col-reverse as an easy way to keep the tab order correct, it should first tab to '-', then '+'.
We then add the event handlers to the buttons using x-on:click, the full code (excluding CSS) is as follows:
<div ... x-data="{ inc() { var e = $refs.spinbox; e.value = Math.min(Number(e.value) + Number(e.step), e.max); }, dec() { var e = $refs.spinbox; e.value = Math.max(Number(e.value) - Number(e.step), e.min); }, isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) } }"> <input ... x-ref="spinbox" x-on:input="$el.value = isNumber($el.value) ? Math.round($el.value) : null"> <div ...> <!-- Decrement input's value --> <button type="button" ... x-on:click="dec">-</button> <!-- Increment input's value --> <button type="button" ... x-on:click="inc">+</button> </div> </div>
We have to convert e.value and e.step before doing any arithmetic as those are strings.
When it comes to CSS for the spinners buttons, they are styled very similarly to the input, the full code is below .
The final template
templ IntSpinbox(name, label, value, tooltip string, saveinput bool, interval *IntInterval) { <!-- Disable inner & outer spinner buttons, use buttons to render increment and decrement input value... --> <div class="flex-1"> @InputLabel(name, label + " " + interval.toString(), tooltip) <input type="number" placeholder="Enter Int…" step="1" if interval nil min="{" strconv.itoa max="{" name="{" value="{" class="block w-full rounded-l-md py-2 px-2.5 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-primary-400 bg-gray-50 sm:text-sm sm:leading-6 select-none [-moz-user-select:none] [-ms-user-select:none] [-o-user-select:none] [-webkit-user-select:none] [&::-webkit-inner-spin-button]:[-webkit-appearance:none] [&::-webkit-outer-spin-button]:[-webkit-appearance:none] [-moz-appearance:textfield]" x-on:input="$el.value = !isNumber($el.value) ? null : Math.round($el.value)" x-ref="spinbox" autocomplete="off"> <div class="flex flex-col-reverse font-medium"> <!-- Decrement input's value --> <button type="button" class="flex-1 px-1 leading-none transition-colors ease-linear duration-100 rounded-br-md text-center text-sm bg-gray-100 hover:bg-gray-200 text-gray-500 hover:text-gray-900 ring-1 ring-inset ring-gray-300 focus:outline-none focus:ring-inset focus:ring-2 focus:ring-primary-400 select-none [-moz-user-select:none] [-ms-user-select:none] [-o-user-select:none] [-webkit-user-select:none]" x-on:click="dec">-</button> <!-- Increment input's value --> <button type="button" class="flex-1 px-1 leading-none transition-colors ease-linear duration-100 rounded-tr-md text-center text-sm bg-gray-100 hover:bg-gray-200 text-gray-500 hover:text-gray-900 ring-1 ring-inset ring-gray-300 focus:outline-none focus:ring-inset focus:ring-2 focus:ring-primary-400 select-none [-moz-user-select:none] [-ms-user-select:none] [-o-user-select:none] [-webkit-user-select:none]" x-on:click="inc">+</button> </div> </div> }
Enjoy :)
Works on
- Mozilla Firefox 130.0 (64-bit)
- Version 128.0.6613.120 (Official Build) (64-bit)
위 내용은 Go/Templ에서 깨끗하고 친숙한 Spinner 만들기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

golangisidealferperperferferferferformance-criticalapplications 및 concurrentprogramming, whilepythonexcelsindatascience, 빠른 프로토 타입, 및 범위

Golang은 Goroutine 및 Channel을 통해 효율적인 동시성을 달성합니다. 1. Goroutine은 가벼운 스레드이며 GO 키워드로 시작합니다. 2. 채널은 경주 조건을 피하기 위해 고루틴 간의 안전한 통신에 사용됩니다. 3. 사용 예제는 기본 및 고급 사용법을 보여줍니다. 4. 일반적인 오류에는 교착 상태와 데이터 경쟁이 포함되며 Gorun-Race가 감지 할 수 있습니다. 5. 성능 최적화는 채널 사용을 줄이고, 고 루틴 수를 합리적으로 설정하고, sync.pool을 사용하여 메모리를 관리하는 것을 제안합니다.

Golang은 시스템 프로그래밍 및 높은 동시성 응용 프로그램에 더 적합한 반면 Python은 데이터 과학 및 빠른 개발에 더 적합합니다. 1) Golang은 Google에 의해 개발되어 정적으로 입력하여 단순성과 효율성을 강조하며 동시성 시나리오에 적합합니다. 2) Python은 Guidovan Rossum, 동적으로 입력, 간결한 구문, 광범위한 응용 프로그램, 초보자 및 데이터 처리에 적합합니다.

Golang은 성능과 확장 성 측면에서 Python보다 낫습니다. 1) Golang의 컴파일 유형 특성과 효율적인 동시성 모델은 높은 동시성 시나리오에서 잘 수행합니다. 2) 해석 된 언어로서 파이썬은 천천히 실행되지만 Cython과 같은 도구를 통해 성능을 최적화 할 수 있습니다.

Go Language는 동시 프로그래밍, 성능, 학습 곡선 등의 고유 한 장점을 가지고 있습니다. 1. 동시 프로그래밍은 가볍고 효율적인 Goroutine 및 채널을 통해 실현됩니다. 2. 컴파일 속도는 빠르며 작동 속도는 작동 성능이 C 언어의 성능에 가깝습니다. 3. 문법은 간결하고 학습 곡선은 매끄럽고 생태계는 풍부합니다.

Golang과 Python의 주요 차이점은 동시성 모델, 유형 시스템, 성능 및 실행 속도입니다. 1. Golang은 동시 작업에 적합한 CSP 모델을 사용합니다. Python은 I/O 집약적 인 작업에 적합한 멀티 스레딩 및 Gil에 의존합니다. 2. Golang은 정적 유형이며 Python은 동적 유형입니다. 3. Golang 컴파일 된 언어 실행 속도는 빠르며 파이썬 해석 언어 개발은 빠릅니다.

Golang은 일반적으로 C보다 느리지 만 Golang은 동시 프로그래밍 및 개발 효율에 더 많은 장점이 있습니다. 1) Golang의 쓰레기 수집 및 동시성 모델은 높은 동시 시나리오에서 잘 수행합니다. 2) C는 수동 메모리 관리 및 하드웨어 최적화를 통해 더 높은 성능을 얻지 만 개발 복잡성이 높습니다.

Golang은 클라우드 컴퓨팅 및 DevOps에서 널리 사용되며 장점은 단순성, 효율성 및 동시 프로그래밍 기능에 있습니다. 1) 클라우드 컴퓨팅에서 Golang은 Goroutine 및 채널 메커니즘을 통해 동시 요청을 효율적으로 처리합니다. 2) DevOps에서 Golang의 빠른 편집 및 크로스 플랫폼 기능이 자동화 도구의 첫 번째 선택입니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Dreamweaver Mac版
시각적 웹 개발 도구

WebStorm Mac 버전
유용한 JavaScript 개발 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경
