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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 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)

Does H5 page production require continuous maintenance? Does H5 page production require continuous maintenance? Apr 05, 2025 pm 11:27 PM

The H5 page needs to be maintained continuously, because of factors such as code vulnerabilities, browser compatibility, performance optimization, security updates and user experience improvements. Effective maintenance methods include establishing a complete testing system, using version control tools, regularly monitoring page performance, collecting user feedback and formulating maintenance plans.

How to select a child element with the first class name item through CSS? How to select a child element with the first class name item through CSS? Apr 05, 2025 pm 11:24 PM

When the number of elements is not fixed, how to select the first child element of the specified class name through CSS. When processing HTML structure, you often encounter different elements...

How to make progress bar with h5 How to make progress bar with h5 Apr 06, 2025 pm 12:09 PM

Create a progress bar using HTML5 or CSS: Create a progress bar container. Set the progress bar width. Create internal elements of the progress bar. Sets the internal element width of the progress bar. Use JavaScript, CSS, or progress bar library to display progress.

What application scenarios are suitable for H5 page production What application scenarios are suitable for H5 page production Apr 05, 2025 pm 11:36 PM

H5 (HTML5) is suitable for lightweight applications, such as marketing campaign pages, product display pages and corporate promotion micro-websites. Its advantages lie in cross-platformity and rich interactivity, but its limitations lie in complex interactions and animations, local resource access and offline capabilities.

How to run the h5 project How to run the h5 project Apr 06, 2025 pm 12:21 PM

Running the H5 project requires the following steps: installing necessary tools such as web server, Node.js, development tools, etc. Build a development environment, create project folders, initialize projects, and write code. Start the development server and run the command using the command line. Preview the project in your browser and enter the development server URL. Publish projects, optimize code, deploy projects, and set up web server configuration.

Is H5 page production a front-end development? Is H5 page production a front-end development? Apr 05, 2025 pm 11:42 PM

Yes, H5 page production is an important implementation method for front-end development, involving core technologies such as HTML, CSS and JavaScript. Developers build dynamic and powerful H5 pages by cleverly combining these technologies, such as using the <canvas> tag to draw graphics or using JavaScript to control interaction behavior.

How to make h5 click icon How to make h5 click icon Apr 06, 2025 pm 12:15 PM

The steps to create an H5 click icon include: preparing a square source image in the image editing software. Add interactivity in the H5 editor and set the click event. Create a hotspot that covers the entire icon. Set the action of click events, such as jumping to the page or triggering animation. Export H5 documents as HTML, CSS, and JavaScript files. Deploy the exported files to a website or other platform.

How to solve the h5 compatibility problem How to solve the h5 compatibility problem Apr 06, 2025 pm 12:36 PM

Solutions to H5 compatibility issues include: using responsive design that allows web pages to adjust layouts according to screen size. Use cross-browser testing tools to test compatibility before release. Use Polyfill to provide support for new APIs for older browsers. Follow web standards and use effective code and best practices. Use CSS preprocessors to simplify CSS code and improve readability. Optimize images, reduce web page size and speed up loading. Enable HTTPS to ensure the security of the website.

See all articles