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

问题描述

使用javascript设置内联CSS值很容易。如果我想改变宽度,我有这样的HTML:

It's easy to set inline CSS values with javascript. If I want to change the width and I have html like this:

<div style="width: 10px"></div>

我需要做的是:

document.getElementById('id').style.width = value;

它将更改内联样式表值。通常这不是问题,因为内联样式会覆盖样式表。示例:

It will change the inline stylesheet values. Normally this isn't a problem, because the inline style overrides the stylesheet. Example:

<style>
   #tId {
      width: 50%;
   }
</style>

<div id="tId"></div>

使用此Javascript:

Using this Javascript:

document.getElementById('tId').style.width = "30%";

我得到以下内容:

<style>
   #tId {
      width: 50%;
   }
</style>

<div id="tId" style="width: 30%";></div>

这是一个问题,因为我不仅不想更改内联值,如果我寻找我设置之前的宽度,当我有:

This is a problem, because not only do I not want to change inline values, If I look for the width before I set it, when I have:

<div id="tId"></div>

返回值为Null,所以如果我有Javascript需要知道要做的事情的宽度一些逻辑(我将宽度增加1%,而不是一个特定的值),当我希望字符串50%不起作用时,返回空值。

The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value), getting back Null when I expect the string "50%" doesn't really work.

所以我的问题:我的CSS样式的值不在内联,我该如何获取这些值?给定一个id,如何修改样式而不是内联值?

So my question: I have values in a CSS style that are not located inline, how can I get these values? How can I modify the style instead of the inline values, given an id?

推荐答案

好的,这听起来像是要改变全球CSS,将一次性有效地改变所有元素的网状风格。我最近学会了如何从。

Ok, it sounds like you want to change the global CSS so which will effictively change all elements of a peticular style at once. I've recently learned how to do this myself from a Shawn Olson tutorial. You can directly reference his code here.

以下是摘要:

您可以检索通过 document.styleSheets 。这将实际返回页面中所有样式表的数组,但您可以通过 document.styleSheets [styleIndex] .href 属性来判断您正在使用哪一个样式表。找到要编辑的样式表后,您需要获取规则数组。这在IE中被称为规则,在大多数其他浏览器中也称为cssRules。告诉您所使用的的方式是由 selectorText 属性。工作代码看起来像这样:

You can retrieve the stylesheets via document.styleSheets. This will actually return an array of all the stylesheets in your page, but you can tell which one you are on via the document.styleSheets[styleIndex].href property. Once you have found the stylesheet you want to edit, you need to get the array of rules. This is called "rules" in IE and "cssRules" in most other browsers. The way to tell what CSSRule you are on is by the selectorText property. The working code looks something like this:

var cssRuleCode = document.all ? 'rules' : 'cssRules'; //account for IE and FF
var rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex];
var selector = rule.selectorText;  //maybe '#tId'
var value = rule.value;            //both selectorText and value are settable.

让我知道这是如何工作的,如果你看到任何错误,请发表评论。

Let me know how this works for ya, and please comment if you see any errors.

这篇关于更改CSS值的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 14:56
查看更多