[JS]使用JS修改标签属性和CSS样式表

/ 12评论 / 1052阅读 / 2点赞

HTML标签的样式


JS方法

这里我们都以开头的div为例子(<div id="cooldiv" class="cdiv"><div>)

修改内联样式:

<script>
/*通过id定位*/
function temp_byId(){
    var mydiv = document.getElementById("cooldiv");
    mydiv.setAttribute("height", "20px");
}

/*通过类名定位*/
function temp_byClassName(){
    var mydivList = document.getElementsByClassName("cdiv");
    for(var i = mydivList.length; i--;){
        mydivList[i].setAttribute("height", "20px");
    }
}
</script>
<script>
function temp(){
    var mydiv = document.getElementById("cooldiv");

    mydiv.style.height = "20px";
    mydiv.style.backgroundColor="#66ccff";
    mydiv.style.color = "#66ccff";
}
</script>

修改样式表:

<script>
function temp(){
    var mydiv = document.getElementById("cooldiv");
    mydiv.style.cssText = " color:#66ccff; height:20px; ";
    /*累加cssText,如果直接等于,则上一句设置的color height会被删掉*/
    mydiv.style.cssText += "; width:20px; ";
}
</script>
/*创建一个<style>标签*/
var mystyle = document.createElement('style');

/*写入<style>内的CSS样式表*/
mystyle.innerHTML =
'.cdiv {' +
'   color: blue;' +
'   background-color: #66ccff;' +
'   height: 20px;' +
'}';

// 获取第一个<script>标签
var ref = document.querySelector('script');
// 在第一个<script>标签前插入<style>标签
ref.parentNode.insertBefore(mystyle, ref);
<style>
/*定义一个新样式类newDiv,写入想要的样式*/
.newDiv {
    color:#66ccff;
    height: 20px;
}
</style>

<script>
/*把新样式类newDiv加到标签上*/
function temp(){
    var mydiv = document.getElementById("cooldiv");
    mydiv.classList.add("newDiv");
}
</script>

  1. Rastrear Celular说道:

    Você também pode personalizar o monitoramento de determinados aplicativos, e ele começará imediatamente a capturar instantâneos da tela do telefone periodicamente.

  2. mkeYyGP说道:

    046 CV event finasteride 5mg no prescription cheap 10 LCD screen with 40 pre loaded gauge designs and themes

  3. Assumpmok说道:

    precio levitra 10 Colonies were then transferred to a conical tube and shaken on ice for an additional 30 min until Matrigel was completely dissolved, collected by centrifugation at 115 g for 2 min and pipetted onto a slide

  4. THATHECOM说道:

    7 mL kg per percentage than predicted by the Parkland formula for adequate resuscitation coupons for cialis 20 mg

  5. grenuenah说道:

    Reduced live birth rate Reduced fertilization rate Fewer eggs Higher rates of miscarriage buy cialis 20mg Therefore, it is mandatory that different treatment approaches be offered to women for whom hormone therapy is contraindicated

  6. VORVOSESK说道:

    The faint voice fell, and the people around were shocked again fertility drugs clomid Oh I hope that Simonetta will never wake up I came to see your wife

  7. VORVOSESK说道:

    EP 1 mRNA is expressed moderately in the muscularis mucosae layer of the stomach when was viagra released

  8. Mark说道:

    Thanks for your blog, nice to read. Do not stop.

回复 VORVOSESK 取消回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注