Common operations of CSS

Time:2020-10-22

Get element width

1. Only inline styles can be obtained

var ele = document.getElementById('element');
console.log ( ele.style.width ); // empty string
console.log(ele.style.height); // '100px'

2. Real time style

MDN data

var ele = document.getElementById('element');
console.log(window.getComputedStyle(ele).width); // '100px'
console.log(window.getComputedStyle(ele).height); // '100px'

3、Element.currentStyle.width/height

The function is the same as the second point. It only exists in the old version of IE (below IE9). In addition to making the old version of IE compatible, do not use it.

4. In addition to obtaining width and height, it can also obtain information such as element position

MDN data

var ele = document.getElementById('element');
console.log(ele.getBoundingClientRect().width); // 100
console.log(ele.getBoundingClientRect().height); // 100

Rounding

1. Rounding

1. // discard the decimal part and keep the integer part
2.  parseInt(5/2)  // 2

2. Round up

1. // round up and add 1 if there is a decimal
2.  Math.ceil(5/2)  // 3

3. Round down

1. // round down and discard the decimal part
2.  Math.floor(5/2)  // 2

4 rounding

1. // rounding
2.  Math.round(5/2)  // 3

Surplus

1. // surplus
2.  6%4  // 2

Recommended Today

Choose react or angular 2

Original addressChoosing between React vs. Angular 2The following is the translation of this article, which can be used at your choiceReactperhapsAngular2We need to help when we need to. React has become a cool representative in 2015, but angular.js has changed from a front-end framework that people love to a terrible devil (and not so terrible…) […]