Home Web Front-end JS Tutorial JavaScript and CSS review ('Mastering JavaScript')_javascript skills

JavaScript and CSS review ('Mastering JavaScript')_javascript skills

May 16, 2016 pm 06:24 PM
css javascript

For example: elem.style.height or elem.style.height = '100px'. It should be noted here that the size unit (such as px) must be specified when setting any geometric properties. At the same time, any geometric properties return a string representing the style instead of A numerical value (e.g. '100px' instead of 100). In addition, operations like elem.style.height can also obtain the style value set in the element's style attribute. If you put the styles in a CSS file, the above method will only return an empty string. In order to obtain the real and final style of the element, the book gives a function

Copy the code The code is as follows:

//get a style property (name) of a specific element (elem)
function getStyle(elem, name) {
 // if the property exists in style[], then it's been set
//recently (and is current)
if(elem.style[name]) return elem.style[name];
//otherwise, try to use IE's method
else if (elem. currentStyle) return elem.currentStyle[name];
//Or the W3C's method, if it exists
else if (document.defaultView && document.defaultView.getComputedStyle) {
   ///it uses the traditional ' text-align' style of rule writing
    //instead of textAlign
name = name.replace(/[A-Z]/g, '-$1');
name = name.toLowerCase();
//get the style object and get the value of the property (if it exists)
  var s = document.defaultView.getComputedStyle(elem,'');
return s && s.getPropertyValue(name) ;
 } else return null;
}

Understanding how to obtain the position of an element on the page is the key to constructing interactive effects. First review the characteristics of the position attribute value in CSS.
static: Static positioning, this is the default way of positioning elements, it simply follows the document flow. But when the element is positioned statically, the top and left attributes are invalid.
relative: Relative positioning, the element will continue to follow the document flow unless affected by other instructions. Setting the top and left attributes causes the element to be offset relative to its original position.
Absolute: Absolute positioning. An absolutely positioned element is completely out of the document flow. It will be displayed relative to its first non-statically positioned ancestor element. If there is no such ancestor element, its positioning will be relative to the entire document. .
fixed: Fixed positioning positions the element relative to the browser window. It completely ignores browser scrollbar dragging.
The author has encapsulated a cross-browser function for obtaining the page position of an element
There are several important element attributes: offsetParent, offsetLeft, offsetTop (you can click directly to the relevant page of the Mozilla Developer Center)
Copy code The code is as follows:

//find the x (horizontal, Left) position of an element
function pageX(elem) {
  //see if we're at the root element, or not
return elem.offsetParent?
//if we can still go up, add the current offset and recurse upwards
 elem.offsetLeft page position of an element
function pageY(elem) {
  //see if we're at the root element, or not
  return elem.offsetParent ?
//if we can still go up, add the current offset and recurse upwards
  elem.offsetTop pageY(elem.offsetParent) :
//otherwise, just get the current offset
elem.offsetTop;
}


We then need to obtain the horizontal and vertical position of the element relative to its parent. Using the element's position relative to its parent, we can add additional elements to the DOM and position them relative to its parent.



Copy code
The code is as follows: //find the horizontal position of an element within its parent function parentX(elem) {
//if the offsetParent is the element's parent, break early
return elem.parentNode == elem.offsetParent ?
elem.offsetLeft :
// otherwise , we need to find the position relative to the entire
// page for both elements, and find the difference
pageX(elem) - pageX(elem.parentNode);
}
//find the vertical positioning of an element within its parent
function parentY(elem) {
  //if the offsetParent is the element's parent, break early
return elem.parentNode == elem.offsetParent ?
 elem .offsetTop :
// otherwise, we need to find the position relative to the entire
// page for both elements, and find the difference
pageY(elem) - pageY(elem.parentNode);
}


The last problem with element position is to obtain the position of the element when positioning the css (non-static) container. With getStyle, this problem is easily solved
Copy code The code is as follows:

//find the left position of an element
function posX(elem) {
 //get the computed style and get the number out of the value
return parseInt(getStyle(elem, 'left'));
}
//find the top position of an element
function posY(elem) {
 / /get the computed style and get the number out of the value
return parseInt(getStyle(elem, 'top'));
}

Next is to set the position of the element, this Very simple.
Copy code The code is as follows:

//a function for setting the horizontal position of an element
function setX(elem, pos) {
  //set the 'left' css property, using pixel units
 elem.style.left = pos 'px';
}
// a function for setting the vertical position of an element
function setY(elem, pos) {
 //set the 'top' css property, using pixel units
 elem.style.top = pos 'px' ;
}

There are two more functions, used to adjust the current position of the element, which are very practical in animation effects
Copy Code The code is as follows:

//a function for adding a number of pixels to the horizontal
//position of an element
function addX( elem, pos) {
  //get the current horz. position and add the offset to it
setX(elem, posX(elem) pos);
}
//a function that can be used to add a number of pixels to the
//vertical position of an element
function addY(elem, pos) {
 //get the current vertical position and add the offset to it
setY (elem, posY(elem) pos);
}

After knowing how to get the position of the element, let’s take a look at how to get the size of the element.
Get the current height and width of the element
Copy code The code is as follows:

function getHeight(elem) {
return parseInt( getStyle(elem, 'height'));
}
function getWidth(elem) {
return parseInt(getStyle(elem, 'width'));
}

In most cases, the above method is sufficient, but problems may arise in some animation interactions. For example, for animations that start at 0 pixels, you need to know in advance how high or wide the element can be. Secondly, when the display attribute of the element is none, you will not get the value. Both of these problems occur when performing animations. For this purpose the author gives functions to obtain the potential height and width of elements.
Copy code The code is as follows:

//요소의 가능한 전체 높이 찾기
function fullHeight(elem) {
 //요소가 표시되면 offsetHeight를 사용하여 높이를 가져옵니다. , getHeight()
 if(getStyle(elem, 'display') != 'none')
   return elem.offsetHeight || getHeight(elem)
//그렇지 않으면 다음과 같이 표시를 처리해야 합니다. 요소가 없으므로 보다 정확한 읽기를 위해 CSS 속성을 재설정합니다.
var old = ResetCSS(elem, {
 display:'',
visibility:'hidden',
position:'absolute '
});
//clientHeigh를 사용하여 요소의 전체 높이를 알아보세요. 아직 작동하지 않으면 getHeight 함수를 사용하세요.
var h = elem.clientHeight ||
/ /마지막으로 CSS의 원래 속성을 복원합니다.
restoreCSS(elem, old)
//요소의 전체 높이를 반환합니다.
return h; //요소의 전체 높이 찾기, 가능한 너비
function fullWidth(elem) {
  // 요소가 표시되면 offsetWidth를 사용하여 너비를 가져옵니다. offsetWidth()를 사용합니다.
if(getStyle(elem, 'display') != 'none')
Return elem.offsetWidth || getWidth(elem)
//그렇지 않으면 디스플레이를 없음으로 처리해야 합니다. 이므로 정확성을 높이기 위해 CSS를 재설정합니다.
var old = ResetCSS(elem, {
 display:'',
visibility:'hidden',
position:'absolute'
읽기 });//clientWidth를 사용하면 요소의 전체 높이를 찾을 수 있습니다. 아직 작동하지 않으면 getWidth 함수를 사용하세요.
var w = elem.clientWidth || getWidth(elem)// 마지막으로 원본 CSS를 복원합니다
restoreCSS(elem , old);
//요소의 전체 너비를 반환합니다.
return w;
}
//CSS 세트를 설정하는 함수입니다. Properties
function ResetCSS(elem, prop) {
var old = {};//각 속성 탐색
for(var i in prop) {
  //이전 속성 값 기록
old[i] = elem.style[i] ;
   //새 값 설정
 elem.style[i] = prop[i];
}
return old; >}
//원래 CSS 속성 복원
function RestoreCSS(elem, prop) {
for(var i in prop)
elem.style[i] = prop[i]
}


그리고 내용이 많아서 내일 계속하겠습니다. 노트북 화면이 너무 작아서 글을 쓸 때마다 계속 전환됩니다. 그리고 앞으로. . . 이제 듀얼 디스플레이를 구입할 시간입니다!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

How to resize bootstrap How to resize bootstrap Apr 07, 2025 pm 03:18 PM

To adjust the size of elements in Bootstrap, you can use the dimension class, which includes: adjusting width: .col-, .w-, .mw-adjust height: .h-, .min-h-, .max-h-

How to use bootstrap button How to use bootstrap button Apr 07, 2025 pm 03:09 PM

How to use the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text

See all articles