简体   繁体   中英

Why can’t I change the styles of my HTML element using JavaScript?

I have a problem, and I made this test code to show you my problem.

What I want to do is to change the styles of the id. But for some reason it doesn't work.

I don't know what's happening and I really need your help. Thanks.

Judging from the picture of your code that you posted ( http://jsfiddle.net is a better option for this sort of thing), your JavaScript is wrong.

x.style.fontSize('20px');

The style object on HTML elements does not have a function called fontSize , it has a property called fontSize . You assign your desired value to it, like this:

x.style.fontSize = '20px';

If you try your original code in eg Chrome with the JavaScript console visible (View > Developer > JavaScript Console), you should see an error when you try to run your original code.

In your original code you are incorrectly referring to the JavaScript properties as methods...

// ORIGINAL/INCORRECT CODE
// x.style.fontSize('20px');
// x.style.fontFamily('arial');
// x.style.color('#008080');
// x.style.border('10px solid #000');

Corrected...

// CORRECTED
// These are properties, NOT methods.
x.style.fontSize = '20px';
x.style.fontFamily = 'arial';
x.style.color = '#008080';
x.style.border = '10px solid #000';

Those style attributes are properties not methods. That is to say, it should not be x.style.fontSize('20px') , but rather x.style.fontSize = '20px' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM