PHP8 —— New String Helpers

新增了三个字符串函数,str_starts_with, str_ends_with, str_contains, PHP 的函数这么方便,很难想象竟然一直没有这几个。 str_starts_with 判断字符串是否以另一个字符串开头,在PHP7以及之前 $id = 'inv_abcdefgh'; $result = strpos($id, 'inv_') === 0; var_dump($result); // true PHP8 中可以直接这么写 $result = str_starts_with($id, 'inv_'); str_ends_with 判断字符串是否以另外一个字符串结尾,在 PHP7 及之前,比较麻烦,通常是这么写 $id = 'abcd_inv'; $result = strpos(strrev($id), strrev('_inv')) === 0; 或者 $result = substr($id, -1 * strlen('_inv')) === '_inv'; 或者上正则吧 $result = preg_match('/_inv$/', $id) === 1; 看起来都是比较麻烦的。PHP8 里面可以简化成下面这样了 $id = 'abcd_inv'; $result = str_ends_with($id, '_ind'); str_contains 字符串包含,PHP8 之前一般就是 strpos 来实现了 $url = 'https://example?for=bar'; $result = strpos($url, '?') !== FALSE; PHP8 就直接一点 $result = str_contains($url, '?');

CSSOM 对象模型

CSSOM is the object model of CSS. In the W3C standard, it contains two parts: the model part (CSSOM) describing CSS such as style sheets and rules, and the view part (CSSOM View) related to element views.
In practice, CSSOM View is more commonly used than CSSOM, because we rarely need to use code to dynamically manage style sheets.
In today's article, I will introduce you to the two parts of the API separately.

CSSOM

First, let's introduce the model of style sheet in CSS, which is the ontology of CSSOM.
We usually create style sheets using HTML tags. We use style tags and link tags to create style sheets. For example:

<style title="Hello">
a {
  color:red;
}
</style>
<link rel="stylesheet" title="x" href="data:text/css,p%7Bcolor:blue%7D">

After we have created the style sheet, we may need to do some operations on it. If we understand it from the perspective of the DOM, these tags are a node in the DOM. They have the content and attributes of the nodes. Among the two tags, some of the CSS code is in attributes and some are in child nodes. These two tags also follow the operation rules of DOM nodes, so they can be accessed using the DOM API.
However, the consequence of this is that we need to write a lot of branch logic, and it is not easy to parse the structure of the CSS code, so in this case, we directly use the CSSOM API to manipulate the style sheets they generate. This is a better choice.
Let's first understand the basic usage of the CSSOM API. In general, we need to get all the style sheets in the document:

document.styleSheets

The styleSheets property of the document represents all the style sheets in the document. This is a read-only list. We can access the style sheet using the square bracket operator subscript, or we can use the item method to access it. It has a length property to represent the style in the document. Number of tables.
Style sheets can only be created using style tags or link tags (for XML, they can also be used, let's leave them alone).
Although we cannot use the CSSOM API to create style sheets, we can modify the content in the style sheets.

document.styleSheets[0].insertRule("p { color:pink; }", 0)
document.styleSheets[0].removeRule(0)

Further, we can get a specific rule in the style sheet and perform certain operations on it, specifically, using its cssRules property to achieve:

document.styleSheets[0].cssRules

The list of rules taken here also supports item, length, and index operations.
However, the Rules here are not so simple. It may be at-rule of CSS, or it may be ordinary style rules. Different rule types have different attributes.
We have compiled a complete list of at-rule for you in the CSS syntax section. Most at-rule correspond to a rule type:

  • CSSStyleRule
  • CSSCharsetRule
  • CSSImportRule
  • CSSMediaRule
  • CSSFontFaceRule
  • CSSPageRule
  • CSSNamespaceRule
  • CSSKeyframesRule
  • CSSKeyframeRule
  • CSSSupportsRule

Specific rules support the attributes. It is recommended that you consult the MDN or W3C documentation when you can use them. In our article, we only introduce the most commonly used CSSStyleRule in detail.
CSSStyleRule has two properties: selectorText and style, which represent the selector part and style part of a rule, respectively.
The selector part is a string. It is obviously lazy to design a further selector model here. We can set it according to the selector syntax.
The style part is a style sheet, which is the same type as the style attribute of our element, so we can directly change the specific CSS attribute definitions in the attribute modification rules like modifying inline styles, or use tool attributes such as cssText.
In addition, CSSOM also provides a very important method to get the attributes of an element that are finally calculated by CSS:

window.getComputedStyle(elt, pseudoElt);

The first parameter is the element we want to get the attribute, and the second parameter is optional and used to select the pseudo-element.
OK, so far, we can use the CSSOM API to freely modify the style sheet that has been in effect on the page. Next, let's focus on the issue of views.

CSSOM View

The CSSOM View API can be regarded as an extension of the DOM API. It adds display-related functions to the original Element interface. These functions can be divided into three parts: the window part, the scroll part, and the layout part. Below Let me show you each.

window API

The window API is used to manipulate the position, size, etc. of the browser window.
moveTo (x, y) moves the window to a specific coordinate of the screen;
moveBy (x, y) moves the window a certain distance;
resizeTo (x, y) changes the window size to a specific size;
resizeBy (x, y) changes the window size to a specific size.
In addition, the window API specifies the third parameter of window.open ():

window.open("about:blank", "_blank" ,"width=100,height=100,left=100,right=100" )

Some browsers are not implemented for security reasons and are not suitable for mobile browsers. You only need to understand this part briefly. Let ’s take a look at the rolling API.
Scrolling API
To understand scrolling, we must first establish a concept. In the PC era, the relationship between the scrolling of the browser's visible area and the scrolling of internal elements is relatively vague, but today it is increasingly important on the mobile side, the two must be separated. In terms of performance, there are differences between the two.

Viewport scrolling API

The viewing area (viewport) scrolling behavior is controlled by a set of APIs on the window object, let's first understand:

  • scrollX is a viewport property, which indicates the current scroll distance in the X direction, and has the alias pageXOffset;
  • scrollY is a viewport property, which indicates the current scroll distance in the Y direction, and has the alias pageYOffset;
  • scroll (x, y) makes the page scroll to a specific position, has the alias scrollTo, and supports configuration parameters {top, left};
  • scrollBy (x, y) makes the page scroll a certain distance, and supports configuration parameters {top, left}.

With these properties and methods, we can read the viewport scroll position and manipulate the viewport scroll. However, to listen for viewport scroll events, we need to bind event listeners to the document object:

document.addEventListener("scroll", function(event){
  //......
})

The viewport scrolling API is the scrolling of the top container of the page. Most mobile browsers will use some performance optimizations, which are not exactly the same as element scrolling. Please be sure to establish this sense of distinction.

Element scrolling API

Next, let's take a look at the element scrolling API. In the Element class (see the DOM section), to support scrolling, the following APIs have been added.

  • The attribute of the scrollTop element, which represents the current scroll distance in the Y direction.
  • The attribute of the scrollLeft element, which represents the current scroll distance in the X direction.
  • The scrollWidth element attribute indicates the width of the scroll content inside the element. Generally, it will be greater than or equal to the element width.
  • The attribute of the scrollHeight element, which represents the height of the scroll content inside the element, and is generally greater than or equal to the element height.
  • scroll (x, y) makes the element scroll to a specific position. It has the alias scrollTo and supports the configuration parameter {top, left}.
  • scrollBy (x, y) makes the element scroll to a specific position, and supports configuration parameters {top, left}.
  • scrollIntoView (arg) The scroll element's parent element, which makes the element scroll to the visible area. You can use arg to specify scrolling to the middle, the beginning, or the nearest.

In addition, scrollable elements also support the scroll event, we can listen to its events on the element:

element.addEventListener("scroll", function(event){
  //......
})

We need to pay attention to this point. The API design of the element part is slightly different from the viewport scrolling naming style. Don't mix it up when you use it.

Layout API

Finally, let's introduce the layout API, which is the most commonly used part of the entire CSSOM. We also want to divide it into global APIs and APIs on elements.

Global size information

The window object provides some global size information, which is provided through properties. Let's take a look at these properties.

  • window.innerHeight, window.innerWidth These two properties represent the size of the viewport.
  • window.outerWidth, window.outerHeight These two properties represent the size occupied by the browser window. Many browsers do not implement them. Generally speaking, these two properties do not matter.
  • window.devicePixelRatio This property is very important, representing the magnification relationship between physical pixels and CSS pixel units. This value is 2 for Retina screens, and some 3x Android screens have also appeared later.
  • window.screen (screen size related information)
  • window.screen.width, window.screen.height The screen size of the device.
  • window.screen.availWidth, window.screen.availHeight The size of the renderable area of the device screen. Some Android machines reserve a part of the screen as fixed buttons, so there are these two properties, which are generally not implemented by browsers. So meticulous.
  • window.screen.colorDepth, window.screen.pixelDepth These two properties have a fixed value of 24 and should be reserved for future use.

Although window has so much related information, in my opinion, we mainly use the three properties of innerHeight, innerWidth and devicePixelRatio, because our front-end development work only needs to deal with the viewport, and other information can probably be understood.

Element layout information

Finally, we come to the question mentioned at the beginning of this lesson. Can we get the width and height of an element?
In fact, we should first eliminate the concept of "elements have width and height" from our brains. We have mentioned many times in the course that some elements may produce multiple boxes. In fact, only boxes have width and height. of.
So we should get the width and height objects as "boxes", so CSSOM View adds two methods to the Element class:

  • getClientRects();
  • getBoundingClientRect()。

getClientRects will return a list containing the rectangular area of the client occupied by each box corresponding to the element. Here, each rectangular area can use x, y, width, height to get its position and size.
getBoundingClientRect, the design of this API is closer to the concept of the element box in our mind. It returns the rectangular area of all boxes corresponding to the element. It should be noted that the area obtained by this API will include the child element area when overflow is visible.
Depending on the actual accuracy requirements, we can choose when to use these two APIs.
The rectangular areas obtained by both APIs are relative to the viewport, which means that these areas are affected by scrolling.
If we want to get the relative coordinates, or the coordinates of the scroll area, we need a little trick:

var offsetX = document.documentElement.getBoundingClientRect().x - element.getBoundingClientRect().x;

As shown in this code, we only need to get the position of the document and the nodes, and then subtract them to get their coordinates.
The compatibility of these two APIs is very good, and the definition is very clear. It is recommended that you use these two APIs as much as possible when implementing visual effects with JavaScript.

评论

此博客中的热门博文

D3js Data-binding basics

JavaScript 数据类型

Vue3新特性(1) —— Vite