Home  >  Article  >  Web Front-end  >  The difference between font-weight and fontWeight in JavaScript

The difference between font-weight and fontWeight in JavaScript

黄舟
黄舟Original
2017-07-22 13:23:303698browse

Today I discovered that the CSS style of an element is set through JS. The code is as follows:

var js = document.getElementById('test-p');
js.style['font-weight'] = 'bold';

Then I discovered a very strange place. . We can use

console.log(js.style.fontWeight);
console.log(js.style['font-weight']);
console.log(js.style['fontWeight']);

to set the bold before console output, or we set js.style.fontWeight = 'bold'; even if we set {font-weight: bold} directly in CSS ; You can also use the above three methods to output the set bold on the console.

If the property 'font-weight' is not found in the object output directly by console.log(js.style);, only 'fontWeight', may I ask why this is and why we have 'font-weight' and 'fontWeight' will appear to be 'equivalent'. Newbies said they were completely confused. Thank you for your answers.

In JS, "-" represents the subtraction operator. So font-weight represents font minus weight, and test-p is equivalent to test minus p.

This is the camel case writing method
js.style.font-weight. If you write it directly like this, it will make an error.
Either write it in the camel case writing method
js.style.fontWeight

or write it in style ['property']

As a browser script, javascript must naturally be able to control things such as css

There is a problem here: many properties of css use - as a connection number, and in javascript, objects There must never be a minus sign in the attribute

So, the clever author had a flash of inspiration: why not use camel case naming to access css properties in js, so that it doesn’t look too frustrating

From now on, when accessing css properties, you can either use camel case naming or use minus signs to connect names

The above is the detailed content of The difference between font-weight and fontWeight in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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