> 웹 프론트엔드 > CSS 튜토리얼 > Peasy-UI로 CSS 제어하기: Peasy-UI 시리즈 f부

Peasy-UI로 CSS 제어하기: Peasy-UI 시리즈 f부

王林
풀어 주다: 2024-09-03 15:04:40
원래의
526명이 탐색했습니다.

Table of Contents

  1. Introduction
  2. Binding CSS Properties
    • Internal CSS
    • Inline CSS
  3. The Three Helpers
    • pui-adding
    • pui-removing
    • Show/Hide Example
    • pui-moving
  4. Conclusion
  5. More information

Introduction

In my latest installment of the Peasy-UI library series we are going to dive another layer deeper. In this entry, we will cover how you can use both internal CSS and inline CSS bindings with Peasy-UI. We also are going cover the CSS helper classes that are made available using Peasy to assist with animations. We will dig into each of the three classes that are available, and we can cover how they can be used in your template and bind elements to these helper classes.

If you missed the introduction article for Peasy-UI, you can read it here, and it can provide the overview for the library, and even introduces upcoming topics in the series.

Binding CSS Properties

In this section, let's cover different strategies of using Peasy-UI's bindings with CSS.

Internal CSS

When I am binding style properties for a Peasy-UI component or small application, my primary approach is to use the standards block above my html that I am using. Let's take a look at a quick example.

In this example I have a toggle button, which when clicked is transitioning the elements position back and forth. The other button functions will be reviewed in their designated sections later.

Controlling CSS with Peasy-UI: Part f the Peasy-UI Series

In my DOM template:

...
<button \${click@=>toggle}>Toggle</button>
...
<test-element></test-element>
...
로그인 후 복사

My CSS for this:

test-element {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 50px;
  aspect-ratio: 1/1;
  background-color: whitesmoke;
  border-radius: 50%;
  transform: translate(-\${leftPercent}px, 150px);
  transition: transform 0.9s ease-in-out, scale 0.9s ease-in-out;
  scale: 1;
}
로그인 후 복사

In my data model, our logic:

const model = {
  toggleFlag: true,
  leftPercent: 0,
  toggle: (_element: HTMLElement, model: any) => {
    if (model.toggleFlag) model.leftPercent = 100;
    else model.leftPercent = 0;
    model.toggleFlag = !model.toggleFlag;
  },
};
로그인 후 복사

When the toggle method is fired by clicking the button, we use the model.toggleFlag to track our toggle state, and also set the model.leftPercent property to different values. This is the first way I bind CSS properties in Peasy-UI. Another trick I use is I can change the color string of CSS property to transition colors as well. As a general reminder, the first parameter of a Peasy-UI callback is the parent element of the event, and if I'm not using it in the current method, I designate it with the _ prefix. For more details on how Peasy-UI binds event callbacks, a prior article addresses it in a deeper context: Event Binding.

test-element {
  ...
  background-color: \${colorString};
  ...
}
로그인 후 복사
  const model = {
    ...
    colorString: "whitesmoke",
    ...
  };
로그인 후 복사

I can just change the string to other css colorstrings to change the elements color, or you can use a hexstring.

Inline CSS

For more complicated CSS manipulation, sometimes I have added bindings to inline class attributes on elements. That way I can bind a string in the data model, and can control specifically what CSS classes I want active on an element. Let's take a look at a quick example.

Controlling CSS with Peasy-UI: Part f the Peasy-UI Series

In this demonstration you see the test element is toggled on its scale property. Let's take a quick look at how I am accomplishing this.

In my DOM template:

...
<button \${click@=>inlinetoggle}>Inline Toggle</button>
...
<test-element class="\${testClassName}"></test-element>
...
로그인 후 복사

my css for this:

test-element {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 50px;
  aspect-ratio: 1/1;
  background-color: whitesmoke;
  border-radius: 50%;
  transform: translate(-\${leftPercent}px, 150px);
  transition: transform 0.9s ease-in-out, scale 0.9s ease-in-out;
  scale: 1;
}

.scaleTestElement {
  scale: 1.5;
}
로그인 후 복사

and in my data model:

export const model = {
  ...
  inlinetoggleFlag: false,
  testClassName: "",
  ...
  inlinetoggle: (_element: HTMLElement, model: any) => {
    if (model.inlinetoggleFlag)  model.testClassName = "";
    else  model.testClassName = "scaleTestElement";
    model.inlinetoggleFlag = !model.inlinetoggleFlag;
  },
};
로그인 후 복사

Let's breakdown what aspects are highlighted here. Let's start with the toggle button being used to trigger the change, that's a simple button element with a click event binding the inlinetoggle method in the data model to the button. When that method is called, the data model uses a toggle flag, model.inlinetoggleFlag to track a toggle state, and it also changes the model.testClassName string. In the template DOM, the test-element has a class attribute with a string binding in it. When you update the string in the data model, the new class gets added to the element, changing the scale property. The transition property of the element covers the scale property as well.

The Three Helpers

This section will describe the functionality and implementation details of three built-in CSS helper classes that are used in Peasy-UI. This features happen natively regardless if they are taken advantage of or not. These three helpers are: pui-adding, pui-removing, and pui-moving. These are CSS class names added to elements that are being manipulated by Peasy-UI, and are available to be leveraged for managing transitions.

pui adding

The pui-adding CSS class is added to an element when it transitions from not rendered to rendered. This can happen in a couple scenarios. If you are adding an element to a list that's rendered with the <=* binding, then that new element receives the pui-adding class. Another means of adding an element is by using the rendering binding === or !==. To review the available bindings for Peasy-UI, you can reference this article on the bindings here:Bindings and Templates: Part 2 of the Peasy-UI series

The duration of the CSS class being adding is until any transitions tied to pui-adding class is complete. Let's take a deeper look at this.

const model = {
  isDivShowing: false,
};

const template = `

<style>
    .child{
      opacity: 1;
      transition: opacity 1.0s;
    }

    .child.pui-adding{
      opacity: 0;
    }
</style>

<div class="parent">
  <div class="child" \#{===isDivShowing}>
      Hello World
  </div>
</div>
`;

UI.create(document.body, model, template);
로그인 후 복사

In this example what you will see is that when you set model.isDivShowing to true, Peasy-UI will add the element to the DOM, starting with the pui-addding class. The pui-adding class will automatically be removed from the element upon the completion of the 1 second CSS transition that is set for the opacity property.

pui removing

You will see that the pui-removing class helper is the opposite of pui-adding.

The pui-removing CSS class is added to an element when it transitions from rendered to not rendered. This can happen in a couple scenarios. If you are removing an element from a list that's rendered with the <=* binding, then that element which is being removed receives the pui-removing CSS class. Another means of removing an element is by using the rendering binding === or !==.

The duration of the class removing is until any transitions tied to pui-removing class is complete. Let's take a deeper look at this.

const model = {
  isDivShowing: true,
};

const template = `

<style>
    .child{
      opacity: 1;
      transition: opacity 1.0s;
    }

    .child.pui-removing{
      opacity: 0;
    }
</style>

<div class="parent">
  <div class="child" \#{===isDivShowing}>
      Hello World
  </div>
</div>
`;

UI.create(document.body, model, template);
로그인 후 복사

In this example, what you will see is that when you set model.isDivShowing to false, Peasy-UI will add the pui-removing class to the element prior to transitioning the element from the DOM. The pui-removing class will remain on the element upon the completion of the 1 second CSS transition that is set for the opacity property, of which the entire element is removed from the DOM completely.

Show Hide Example

In this example we are working with a DOM template that renders this:

<div>
    <div class="controls">
        <button \${click@=>hide}>Hide</button>
        <button \${click@=>show}>Show</button>
        <button \${click@=>move}>Move</button>
    </div>
    <element-container>
        <inner-element \${el<=*elements}>
            \${el.id}
        </inner-element>
    </element-container>
</div>
로그인 후 복사

In this example, we have replaced standard

elements with more custom names to assist in clarity. and are just elements in practice.

You can see the inner-element div has a list binding that takes the elements array and lists out an inner-element for each item in the list, and places the .id property of each object into the content for the element.

For the sake of this quick demo, we are using a fixed data model: (showing only the elements array)

export const model = {
  elements: [
    {
      id: 1,
    },
    {
      id: 2,
    },
    {
      id: 3,
    },
  ],
  //... click bindings below
로그인 후 복사

What is important here is the CSS styling we added to the rendered template

inner-element {
  ...
  /*other properties that aren't relevant above*/
  transition: opacity 0.9s, background-color 1.2s;
  opacity: 1;
  background-color: whitesmoke;
}

inner-element.pui-adding {
  opacity: 0;
}

inner-element.pui-removing {
  opacity: 0;
}
로그인 후 복사

In the click handlers for the Hide and Show buttons, we are removing and adding the elements from the array. Nothing fancy, but it exercises how Peasy-UI uses the helper classes to manage the CSS transitions. Either helper CSS classes are added, and then the opacity transition of 0.9 seconds starts, then the class is removed. This is how you can use Peasy-UI to manage element transitions.

Controlling CSS with Peasy-UI: Part f the Peasy-UI Series

pui moving

The pui-moving CSS class is added to an element when the element is a part of a list or array, and moves indexes within that list.

The duration of the class adding is until any transitions tied to pui-moving class is complete. Let's take a quick look at this.

In this example, we will call a function that changes the order in the list of elements. When we change the index positions, the pui-moving class will be added to the element. We are using the .pui-moving class to change the elements red that are moving, and this transition happens over time. After the transition period, the array is rendered with the updated order to the DOM.

Controlling CSS with Peasy-UI: Part f the Peasy-UI Series

Our DOM template:

<button \${click@=>move}>Move</button>
<element-container>
  <inner-element \${el<="*elements}"> \${el.id} </inner-element>
</element-container>
로그인 후 복사

Our CSS:

inner-element {
  width: 100px;
  aspect-ratio: 1/1;
  background-color: whitesmoke;
  border-radius: 50%;
  color: black;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  transition: opacity 0.9s, background-color 1.2s, left 0.9s;
  opacity: 1;
  scale: 1;
  left: 0px;
}

inner-element.pui-moving {
  background-color: red;
}
로그인 후 복사

and our DOM model logic:

const model ={
  elements: [...],
   move: (_element: HTMLElement, model: any) => {
    if (model.elements.length > 0) {
      if (model.elements[0].id === 1) {
        moveElement(model.elements, 0, 2);
      } else {
        moveElement(model.elements, 2, 0);
      }
    }
  },
};

function moveElement(array: any[], fromIndex: number, toIndex: number) {
  const element = array.splice(fromIndex, 1)[0]; 
  array.splice(toIndex, 0, element); position
}
로그인 후 복사

We have a button element that triggers a toggle of sorts, but only based on the content of the elements array in the data model. If the element in the zero index position has an id of 1, then we move that element to the 3rd position, index 2. Otherwise, we move the element from index 2 into index 0. One observation that can be made, is that moving one element actually forces all the elements in this example to move, therefore, all three elements get the pui-moving class added.

결론

이 Peasy-UI 시리즈 기사에서 초점은 CSS입니다. 코드 샘플과 예제를 통해 내부 및 인라인 CSS 바인딩을 살펴보았습니다. 다음으로 사용할 수 있는 세 가지 CSS 도우미 클래스인 pui-adding, pui-removing 및 pui-moving에 대해 논의했습니다. 이 기사의 예제는 간단하지만 DOM에 대한 정교한 수준의 제어를 제공하기 위해 어떻게 적용할 수 있는지 확인할 수 있습니다.

다음 항목에서는 Peasy-UI의 가장 복잡한 개념을 파헤쳐 Peasy-UI를 사용하여 재사용 가능한 구성 요소를 만드는 작은 단위로 나누어 보겠습니다.

추가 정보

Peasy-Lib에 대한 GitHub 저장소에서 자세한 내용을 확인할 수 있으며, 다른 모든 동반 패키지도 여기에서 찾을 수 있습니다. 또한 Peasy에는 Discord 서버가 있어 Peasy에 대해 토론하고 서로 도움을 주고받을 수 있습니다.

작가 트위터: 여기

작가의 가려움증: 여기

Peasy-UI Github 저장소: 여기

Peasy Discord 서버: 여기

위 내용은 Peasy-UI로 CSS 제어하기: Peasy-UI 시리즈 f부의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿