本文介绍了使用JavaScript动态更改元素样式属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div的样式表。现在我想使用js动态修改div的一个属性。



我该怎么做?

  document.getElementById(xyz)。style.padding-top =10px; 

这是否正确?



由于 - 是一个javascript操作符,您可以在属性名称中真的有。如果你正在设置, border 或者像这样的单个字样,你的代码将正常工作。



但是,对于 padding-top 和任何连字符属性名称,你需要记住的是,在javascript中,你删除连字符,并使下一个字母大写,所以在你的情况下, paddingTop



还有一些其他的例外。 JavaScript有一些保留字,所以你不能像这样设置 float 。相反,在某些浏览器中,您需要使用 cssFloat ,而在其他 styleFloat 。这是为了像这样的差异,建议您使用一个框架,如jQuery,处理浏览器不兼容为您...


I hav a certain style sheet for a div. Now i want to modify one attribute of div dynamically using js.

How can i do it?

document.getElementById("xyz").style.padding-top = "10px";

Is this correct?

解决方案

It's almost correct.

Since the - is a javascript operator, you can't really have that in property names. If you were setting, border or something single-worded like that instead, your code would work just fine.

However, the thing you need to remember for padding-top, and for any hyphenated attribute name, is that in javascript, you remove the hyphen, and make the next letter uppercase, so in your case that'd be paddingTop.

There are some other exceptions. JavaScript has some reserved words, so you can't set float like that, for instance. Instead, in some browsers you need to use cssFloat and in others styleFloat. It is for discrepancies like this that it is recommended that you use a framework such as jQuery, that handles browser incompatibilities for you...

这篇关于使用JavaScript动态更改元素样式属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 15:12