6

以下のコードでは、私が達成しようとしていることを説明しています... 新しいルールを追加して既存の CSS クラスを変更します。

<head>
<style> 

h4.icontitle
{font-size: 22pt;}

</style>
</head>
<body>
<script type="text/javascript">

textpercent = 84;
document.styleSheets[1].cssRules.['h4.icontitle'].style.setProperty('-webkit-text-size-adjust', textpercent+'%', null);

</script>

<h4> hello </h4>

</body>

これは、さまざまなサイズの画面で実行されるサイトの前処理要素用です。結果は...

h4.icontitle
{font-size: 22pt;
-webkit-text-size-adjust:84%;}

DOM を検査するときに表示されます。

どんなアイデアでも大歓迎です。Javascript のみ - ここには JQuery はありません...

解決しました。

多くの試行錯誤の後、JavaScript がスタイルを CSS に直接挿入できるようにする実用的な関数を次に示します。

function changeCSS(typeAndClass, newRule, newValue)
{
    var thisCSS=document.styleSheets[0]
    var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules
    for (i=0; i<ruleSearch.length; i++)
    {
        if(ruleSearch[i].selectorText==typeAndClass)
        {
            var target=ruleSearch[i]
            break;
        }
    }
    target.style[newRule] = newValue;
}

と呼ばれる

    changeCSS("h4.icontitle","backgroundColor", "green");

うまくいけば、純粋な JavaScript で CSS 内の変数を使用するために、これが便利な方法であることが他の人にもわかるでしょう。

4

4 に答える 4

4

この機能は、私のサイトでは完璧に機能します。

function changeCSS(typeAndClass, newRule, newValue)
{
    var thisCSS=document.styleSheets[0]
    var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules
    for (i=0; i<ruleSearch.length; i++)
    {
        if(ruleSearch[i].selectorText==typeAndClass)
        {
            var target=ruleSearch[i]
            break;
        }
    }
    target.style[newRule] = newValue;
}

と呼ばれる

    changeCSS("h4.icontitle","backgroundColor", "green");
于 2013-08-24T21:53:43.157 に答える
2
/**
Use this to update style tag contents
**/
var css = 'h1 { background: grey; }',
head = document.getElementsByTagName('head')[0],
style = document.createElement('style');

style.type = 'text/css';
if (style.styleSheet){
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}

head.appendChild(style);

body 内の要素を操作するには、querySelector を使用して、CSS 識別子に基づいて要素を対象にします。これはあなたに役立つはずです https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector

var el = document.querySelector(".icontitle");
el.setAttribute("style","-webkit-text-size-adjust:84%");

または、css スニペットを準備して条件付きで使用することもできます。たとえば、「new_css」が新しい変更の場合

/**css code in style tag**/
.icontitle{

  /**style at initial stage**/

}
.icontitle-new-modified{

 /**modified css style at later stage**/

}

//after a condition is satisfied
el.setAttribute("class","icontitle-new-modified");
于 2013-08-24T19:30:49.127 に答える
1

あなたのニーズに合った例をまとめました

デモjsFiddle

// this gets all h4 tags
var myList = document.getElementsByTagName("h4"); // get all p elements

// this loops through them until it finds one with the class 'icontitle' then it assigns the style to it
var i = 0;
while(i < myList.length) {
    if(myList[i].className == "icontitle") {
        myList[i].style.color="red";
    }
    i++;
}
于 2013-08-24T20:09:43.333 に答える